package com.utopiaindustries.querybuilder.ctp;

import com.utopiaindustries.querybuilder.QueryBuilder;
import com.utopiaindustries.util.CTPDateTimeFormat;
import com.utopiaindustries.util.StringUtils;

import java.time.LocalDate;
import java.util.List;

public class SummaryInventoryReportQueryBuilder {
    private final static String TABLE_NAME = " cut_to_pack.inventory_transaction_leg ";

    public static String buildQuery(String itemId,
                                    String sku,
                                    String startDate,
                                    String endDate) {

        // format date
        String formattedDate;
        String formattedEndDate;
        String startDate1 = "";
        String endDate1 = "";
        String itemId1 = "";
        String sku1 = "";
        
        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 23:59:59'", formattedEndDate);
            } else {
                endDate1 = String.format("'%s 23:59:59'", LocalDate.now());
            }
        }
        
        if (!StringUtils.isNullOrEmpty(itemId)) {
            itemId1 = itemId;
        }

        if (!StringUtils.isNullOrEmpty(sku)) {
            sku1 = sku;
        }

        QueryBuilder qb = new QueryBuilder()
                .setTable(TABLE_NAME) 
                .setColumns("item_id, DATE(transaction_leg_datetime) AS transaction_date, sku, parent_document_type, parent_document_piece_type, "
                        + "SUM(CASE WHEN type = 'IN' THEN 1 ELSE 0 END) AS total_in, "
                        + "SUM(CASE WHEN type = 'OUT' THEN 1 ELSE 0 END) AS total_out")
                .where()
                .bracketOpen()
                .bracketOpen()
                .columnEquals("sku", sku1)
                .or()
                .columnIsNull("sku")
                .bracketClose()
                .or()
                .bracketOpen()
                .columnEquals("item_id",itemId)
                .or()
                .columnIsNull("item_id")
                .bracketClose()
                .bracketClose()
                .and()
                .columnBetween("transaction_leg_date",startDate,endDate)
                .groupBy("DATE(transaction_leg_datetime), sku, parent_document_type, parent_document_piece_type")
                .orderBy("transaction_date,", "sku");

        return qb.build();

    }
}