package com.erp.service;

import com.erp.common.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DeliveryService extends BaseService {

    @Autowired private CommonService commonService;

    private static final String NS = "delivery.";

    public Map<String, Object> getDeliveryStatus(Map<String, Object> params) {
        commonService.applyCompanyCodeFilter(params);
        List<Map<String, Object>> deliveries = sqlSession.selectList(NS + "getDeliveryList", params);
        List<Map<String, Object>> issues = sqlSession.selectList(NS + "getCustomerIssueList", params);
        Map<String, Object> todayStats = sqlSession.selectOne(NS + "getDeliveryTodayStats", params);

        Map<String, Object> result = new HashMap<>();
        result.put("deliveries", deliveries);
        result.put("issues", issues);
        result.put("today_stats", todayStats);
        return result;
    }

    public List<Map<String, Object>> getDelayedDeliveries(Map<String, Object> params) {
        commonService.applyCompanyCodeFilter(params);
        return sqlSession.selectList(NS + "getDelayedDeliveryList", params);
    }

    public List<Map<String, Object>> getCustomerIssues(Map<String, Object> params) {
        commonService.applyCompanyCodeFilter(params);
        return sqlSession.selectList(NS + "getCustomerIssueList", params);
    }

    @Transactional
    public void updateDeliveryStatus(Map<String, Object> params) {
        commonService.applyCompanyCodeFilter(params);
        int rows = sqlSession.update(NS + "updateDeliveryStatus", params);
        if (rows == 0) {
            throw new IllegalArgumentException("Delivery not found: " + params.get("id"));
        }
    }

    @Transactional
    public void updateIssueStatus(Map<String, Object> params) {
        commonService.applyCompanyCodeFilter(params);
        int rows = sqlSession.update(NS + "updateCustomerIssueStatus", params);
        if (rows == 0) {
            throw new IllegalArgumentException("Customer issue not found: " + params.get("id"));
        }
    }
}
