package com.ga.batch.settlement.step;

import com.ga.batch.settlement.SettlementContext;
import com.ga.core.mapper.ledger.RecruitLedgerMapper;
import com.ga.core.mapper.product.InsuranceCompanyMapper;
import com.ga.core.mapper.settle.ReconciliationMapper;
import com.ga.core.vo.product.InsuranceCompanyVO;
import com.ga.core.vo.settle.ReconciliationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * Step 3 — reconcile: 보험사 통보액 vs 시스템 계산액 대사
 */
@Slf4j
@Component
@JobScope
@RequiredArgsConstructor
public class ReconcileStep implements Tasklet {

    private final SettlementContext ctx;
    private final InsuranceCompanyMapper companyMapper;
    private final RecruitLedgerMapper recruitMapper;
    private final ReconciliationMapper reconMapper;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        log.info("[Step3 reconcile] settleMonth={}", ctx.getSettleMonth());
        int diff = 0;
        for (InsuranceCompanyVO c : companyMapper.selectActive()) {
            BigDecimal systemTotal = recruitMapper.sumByMonth(ctx.getSettleMonth());
            // 회사 통보액 — 실제로는 raw_commission_data 의 합계로 계산. 여기선 systemTotal 과 동일 처리.
            BigDecimal companyTotal = systemTotal;

            ReconciliationVO r = new ReconciliationVO();
            r.setCompanyCode(c.getCompanyCode());
            r.setSettleMonth(ctx.getSettleMonth());
            r.setCompanyTotal(companyTotal);
            r.setSystemTotal(systemTotal);
            r.setDiffAmount(companyTotal.subtract(systemTotal));
            r.setDiffCount(0);
            r.setStatus(r.getDiffAmount().signum() == 0 ? "MATCHED" : "DIFF");
            reconMapper.upsert(r);
            if ("DIFF".equals(r.getStatus())) diff++;
        }
        ctx.setReconcileDiffCount(diff);
        log.info("[Step3] reconcile diff companies: {}", diff);
        return RepeatStatus.FINISHED;
    }
}
