package com.utopiaindustries.service;

import com.utopiaindustries.dao.ctp.SummaryInventoryReportDao;
import com.utopiaindustries.model.ctp.SummaryInventoryReport;
import com.utopiaindustries.util.CTPDateTimeFormat;
import com.utopiaindustries.util.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

@Service
public class SummaryInventoryReportService {

    private final SummaryInventoryReportDao summaryInventoryReportDao;

    public SummaryInventoryReportService(SummaryInventoryReportDao summaryInventoryReportDao) {
        this.summaryInventoryReportDao = summaryInventoryReportDao;
    }

    public Map<String, Map<String, List<SummaryInventoryReport>>> findByFilter(String itemId, String sku, String startDate, String endDate){
        String formattedDate;
        String formattedEndDate;
        String startDate1 = null;
        String endDate1 = null;
        Integer itemId1 = null;
        String sku1 = null;
        if (!StringUtils.isNullOrEmpty(startDate)) {
            formattedDate = CTPDateTimeFormat.getMySQLFormattedDateString(startDate, CTPDateTimeFormat.HTML5_DATE_INPUT_FORMAT);
            formattedEndDate = CTPDateTimeFormat.getMySQLFormattedDateString(endDate, CTPDateTimeFormat.HTML5_DATE_INPUT_FORMAT);
            startDate1 = String.format("'%s 00:00:01'", formattedDate);
            if (!StringUtils.isNullOrEmpty(endDate)) {
                endDate1 = String.format("'%s 00:00:01'", formattedEndDate);
            } else {
                endDate1 = String.format("'%s 23:59:59'", LocalDate.now());
            }
        }
        if (!StringUtils.isNullOrEmpty(itemId)) {
            itemId1 = Integer.valueOf(itemId);
        }

        if (!StringUtils.isNullOrEmpty(sku)) {
            sku1 = sku;
        }
        List<SummaryInventoryReport> summaries =  summaryInventoryReportDao.findByFilter(itemId1, sku1, startDate1, endDate1);

        Map<String, Map<String, List<SummaryInventoryReport>>> skuMapDateMap = new HashMap<>();

       if(summaries == null) {
           skuMapDateMap = null;
       }else {
           for (SummaryInventoryReport summary : summaries) {
               skuMapDateMap
                       .computeIfAbsent(summary.getSku(), k -> new HashMap<>()) // SKU as key
                       .computeIfAbsent(summary.getDate(), d -> new ArrayList<>()) // Date as key
                       .add(summary);
           }
       }
        return skuMapDateMap;
    }

}
