package com.utopiaindustries.dao.ctp;

import com.utopiaindustries.model.ctp.FinishedItem;
import com.utopiaindustries.model.ctp.StitchingOfflineItem;
import com.utopiaindustries.util.KeyHolderFunctions;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Repository
public class FinishedItemDAO {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String TABLE_NAME = "cut_to_pack.finished_item";
    private final String SELECT_QUERY = String.format("SELECT * FROM %s WHERE id = :id", TABLE_NAME);
    private final String SELECT_ALL_QUERY = String.format("SELECT * FROM %s ORDER BY id DESC", TABLE_NAME);
    private final String SELECT_QUERY_BY_BARCODE_QA_STATUS =String.format("SELECT CASE WHEN EXISTS (SELECT 1 FROM %s WHERE barcode = :barcode AND (is_store = TRUE OR is_packed = TRUE)) THEN TRUE ELSE FALSE END AS result", TABLE_NAME);
    private final String SELECT_QUERY_BY_JOB_CARD = String.format("SELECT * FROM %s WHERE job_card_id = :job_card_id", TABLE_NAME);
    private final String DELETE_QUERY = String.format("DELETE FROM %s WHERE id = :id", TABLE_NAME);
    private final String INSERT_QUERY = String.format("INSERT INTO %s (id, item_id, sku, barcode, created_at, created_by, job_card_id, is_qa, stitched_item_id, is_segregated, qa_status, is_packed, operation_date, is_store) VALUES (:id, :item_id, :sku, :barcode, :created_at, :created_by, :job_card_id, :is_qa, :stitched_item_id, :is_segregated, :qa_status, :is_packed, :operation_date, :is_store) ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), sku = VALUES(sku), barcode = VALUES(barcode), created_at = VALUES(created_at), created_by = VALUES(created_by), job_card_id = VALUES(job_card_id), is_qa = VALUES(is_qa), stitched_item_id = VALUES(stitched_item_id), is_segregated = VALUES(is_segregated), qa_status = VALUES(qa_status), is_packed = VALUES(is_packed), operation_date = VALUES(operation_date), is_store = VALUES(is_store)", TABLE_NAME);
    private final String SELECT_BY_LIMIT = String.format("SELECT * FROM %s ORDER BY id DESC LIMIT :limit", TABLE_NAME);
    private final String SELECT_BY_IDS = String.format("SELECT * FROM %s WHERE id IN (:ids)", TABLE_NAME);
    private final String FIND_TOTAL_COUNT = String.format("SELECT COUNT(*) FROM %s  where job_card_id = :job_card_id And item_id = :item_id", TABLE_NAME);
    private final String SELECT_BY_TERM = String.format("SELECT * FROM %s WHERE barcode LIKE :term AND is_qa = :is_qa AND is_packed = FALSE AND is_store = FALSE ORDER BY ID DESC", TABLE_NAME);
    private final String SELECT_BY_TERM_FOR_PACKAGING = String.format("SELECT * FROM %s WHERE barcode LIKE :term AND is_segregated = :is_segregated AND qa_status = :qa_status AND is_packed = FALSE AND is_store = FALSE ORDER BY ID DESC", TABLE_NAME);
    private final String SELECT_BY_STITCHED_ITEM_ID = String.format("SELECT * FROM %s WHERE stitched_item_id = :stitched_item_id AND is_packed = FALSE", TABLE_NAME);
    private final String SELECT_BY_STITCHED_ITEM_IDS = String.format("SELECT * FROM %s WHERE stitched_item_id IN (:stitched_item_ids)", TABLE_NAME);
    private final String COUNT_TOTAL_FINISH_ITEM = String.format("SELECT COUNT(*) FROM %s WHERE job_card_id = :job_card_id AND is_qa = TRUE AND (is_segregated IS TRUE OR is_store = TRUE) ", TABLE_NAME);
    private final String SELECT_BY_JOB_CARD_AND_DATE = String.format("SELECT * FROM %s WHERE job_card_id = :job_card_id AND (:start_date IS NULL OR :end_date IS NULL OR created_at BETWEEN :start_date AND :end_date)", TABLE_NAME);
    private final String SELECT_BY_DATE_QA_STATUS = String.format( "SELECT COUNT(*) FROM %s WHERE (:start_date IS NULL OR operation_date >= :start_date) AND operation_date <= :end_date AND qa_status = :qa_status AND id in (:ids) AND is_packed = FALSE AND is_qa = TRUE", TABLE_NAME );

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

    // prepare query params
    private MapSqlParameterSource prepareInsertQueryParams(FinishedItem finishedItem) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("id", finishedItem.getId())
                .addValue("item_id", finishedItem.getItemId())
                .addValue("sku", finishedItem.getSku())
                .addValue("barcode", finishedItem.getBarcode())
                .addValue("created_at", finishedItem.getCreatedAt())
                .addValue("created_by", finishedItem.getCreatedBy())
                .addValue("job_card_id", finishedItem.getJobCardId())
                .addValue("is_qa", finishedItem.getIsQa())
                .addValue("stitched_item_id", finishedItem.getStitchedItemId())
                .addValue("is_segregated", finishedItem.getIsSegregated())
                .addValue("qa_status", finishedItem.getQaStatus())
                .addValue("is_packed", finishedItem.isPackaging())
                .addValue("is_store", finishedItem.isStore())
                .addValue("operation_date", finishedItem.getOperationDate());
        return params;
    }

    // find
    public FinishedItem find(long id) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("id", id);
        return namedParameterJdbcTemplate.query(SELECT_QUERY, params, new FinishedItemRowMapper())
                .stream()
                .findFirst()
                .orElse(new FinishedItem());
    }

    // find all
    public List<FinishedItem> findAll() {
        return namedParameterJdbcTemplate.query(SELECT_ALL_QUERY, new FinishedItemRowMapper());
    }

    // save
    public long save(FinishedItem finishedItem) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        MapSqlParameterSource params = prepareInsertQueryParams(finishedItem);
        namedParameterJdbcTemplate.update(INSERT_QUERY, params, keyHolder);
        return KeyHolderFunctions.getKey(finishedItem.getId(), keyHolder);
    }

    // save all
    public int[] saveAll(List<FinishedItem> finishedItems) {
        List<MapSqlParameterSource> batchArgs = new ArrayList<>();
        for (FinishedItem finishedItem : finishedItems) {
            MapSqlParameterSource params = prepareInsertQueryParams(finishedItem);
            batchArgs.add(params);
        }
        return namedParameterJdbcTemplate.batchUpdate(INSERT_QUERY, batchArgs.toArray(new MapSqlParameterSource[finishedItems.size()]));
    }

    // delete
    public boolean delete(long id) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("id", id);
        return namedParameterJdbcTemplate.update(DELETE_QUERY, params) > 0;
    }

    public List<FinishedItem> findByLimit(Long count) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("limit", count);
        return namedParameterJdbcTemplate.query(SELECT_BY_LIMIT, params, new FinishedItemRowMapper());
    }

    public List<FinishedItem> findByQuery(String query) {
        return namedParameterJdbcTemplate.query(query, new FinishedItemRowMapper());
    }

    public List<FinishedItem> findByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) return new ArrayList<>();
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("ids", ids);
        return namedParameterJdbcTemplate.query(SELECT_BY_IDS, params, new FinishedItemRowMapper());
    }

    public List<FinishedItem> findByTerm(String term, boolean isQa) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("term", "%" + term + "%");
        params.addValue("is_qa", isQa);
        return namedParameterJdbcTemplate.query(SELECT_BY_TERM, params, new FinishedItemRowMapper());
    }

    public List<FinishedItem> findByTermForPackaging(String term, boolean isSegregated, String qaStatus) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("term", "%" + term + "%");
        params.addValue("is_segregated", isSegregated);
        params.addValue("qa_status", qaStatus);
        return namedParameterJdbcTemplate.query(SELECT_BY_TERM_FOR_PACKAGING, params, new FinishedItemRowMapper());
    }

    // find By job card Id
    public List<FinishedItem> findByJobCardId(long jobCardId) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("job_card_id", jobCardId);
        return namedParameterJdbcTemplate.query(SELECT_QUERY_BY_JOB_CARD, params, new FinishedItemRowMapper());
    }

    public FinishedItem findByStitchedItem(long stitchedItemId) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("stitched_item_id", stitchedItemId);
        return namedParameterJdbcTemplate.query(SELECT_BY_STITCHED_ITEM_ID, params, new FinishedItemRowMapper())
                .stream()
                .findFirst()
                .orElse(null);

    }

    public HashMap<Long, Long> findTotalFinishedItems(List<Long> itemIds, long jobCardId) {
        HashMap<Long, Long> totalCounts = new HashMap<>();
        MapSqlParameterSource params = new MapSqlParameterSource();
        for (long id : itemIds) {
            params.addValue("job_card_id", jobCardId);
            params.addValue("item_id", id);
            Long total = namedParameterJdbcTemplate.queryForObject(FIND_TOTAL_COUNT, params, Long.class);
            if (total != null) {
                totalCounts.put(id, total);
            }
        }
        return totalCounts;
    }

    public List<FinishedItem> findByStitchedItemIds(List<Long> stitchedItemIds) {
        if (stitchedItemIds == null || stitchedItemIds.isEmpty()) return new ArrayList<>();
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("stitched_item_ids", stitchedItemIds);
        return namedParameterJdbcTemplate.query(SELECT_BY_STITCHED_ITEM_IDS, params, new FinishedItemRowMapper());
    }

    public List<StitchingOfflineItem> findByBarcodeAndApprovedStatus(List<StitchingOfflineItem> stitchingOfflineItems) {
        List<StitchingOfflineItem> items = new ArrayList<>();
        for (StitchingOfflineItem item : stitchingOfflineItems) {
            MapSqlParameterSource params = new MapSqlParameterSource();
            params.addValue("barcode", item.getBarcode());
            boolean check = Boolean.TRUE.equals(namedParameterJdbcTemplate.queryForObject(SELECT_QUERY_BY_BARCODE_QA_STATUS, params, Boolean.class));
            if (!check) {
                items.add(item);
            }
        }
        return items;
    }

    public Long calculateTotalFinishItem(long jobCardId) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("job_card_id", jobCardId);
        Long count = namedParameterJdbcTemplate.queryForObject(COUNT_TOTAL_FINISH_ITEM, params, Long.class);
        return count != null ? count : 0;
    }

    public List<FinishedItem> calculateTotalFinishItem(long jobCardId, String startDate, String endDate) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("job_card_id", jobCardId);
        params.addValue("start_date", startDate);
        params.addValue("end_date", endDate);
        return namedParameterJdbcTemplate.query(SELECT_BY_JOB_CARD_AND_DATE, params, new FinishedItemRowMapper());
    }

    public Long findByOperationDateAndIdsAndQaStatus(String startDate, String endDate, String qaStatus, List<Long> ids){
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue( "start_date", startDate );
        params.addValue( "end_date", endDate );
        params.addValue( "qa_status", qaStatus );
        params.addValue( "ids", ids );
        Long count = namedParameterJdbcTemplate.queryForObject(SELECT_BY_DATE_QA_STATUS, params, Long.class);
        return count != null ? count : 0;
    }

}