package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.SummaryInventoryReport;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class SummaryInventoryReportDao {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String TABLE_NAME = "cut_to_pack.inventory_transaction_leg ";
    String SELECT_QUERY = "SELECT job_card_id, item_id, account_id, parent_document_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 "
            + "FROM " + TABLE_NAME + " "
            + "WHERE "
            + "(:sku IS NULL OR sku = :sku) "
            + "AND (:item_id IS NULL OR item_id = :item_id) "
            + "OR (:start_date IS NULL OR :end_date IS NULL OR transaction_leg_datetime BETWEEN :start_date AND :end_date) "
            + "GROUP BY DATE(transaction_leg_datetime), account_id, sku, parent_document_type, parent_document_piece_type "
            + "ORDER BY transaction_date, sku;";

    public SummaryInventoryReportDao(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    //find by filter for reporting
    public List<SummaryInventoryReport>  findByFilter(Integer itemId, String sku, String startDate, String endDate) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("sku", sku);
        params.addValue("item_id", itemId);
        params.addValue("start_date", startDate);
        params.addValue("end_date", endDate);

        // Query the database and map the result
        List<SummaryInventoryReport> results = namedParameterJdbcTemplate.query(SELECT_QUERY, params, new SummaryInventoryReportRowMapper());

        return results.isEmpty() ? null : results;
    }
}
