package com.ga.batch.settlement.step;

import com.ga.batch.settlement.SettlementContext;
import com.ga.core.mapper.tax.VatReportMapper;
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;

/**
 * Step 12 (conditional) — vatReportQuarterly: 분기 부가세 집계
 *
 * 분기 마감월(3/6/9/12월)에만 실행 (settleMonth ends with "03"/"06"/"09"/"12").
 * tax_invoice 테이블 기준 해당 분기 SUPPLY/PURCHASE SUM → vat_report UPSERT (분기 1건).
 * SQL은 VatReportMapper.upsertAggregate에 위임.
 */
@Slf4j
@Component
@JobScope
@RequiredArgsConstructor
public class VatReportQuarterlyStep implements Tasklet {

    private final SettlementContext ctx;
    private final VatReportMapper vatMapper;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        String settleMonth = ctx.getSettleMonth();

        if (!isQuarterClose(settleMonth)) {
            log.info("[VatReportQuarterly] skipped — not a quarter-close month: {}", settleMonth);
            return RepeatStatus.FINISHED;
        }

        String quarter = toQuarter(settleMonth);
        log.info("[VatReportQuarterly] aggregating VAT for quarter={}", quarter);

        int rows = vatMapper.upsertAggregate(quarter);
        log.info("[VatReportQuarterly] vat_report upserted: {} rows", rows);
        return RepeatStatus.FINISHED;
    }

    /** 정산월이 분기 마감월(03/06/09/12)인지 확인 */
    private boolean isQuarterClose(String settleMonth) {
        if (settleMonth == null) return false;
        // 형식: yyyyMM (예: 202503) 또는 yyyy-MM
        String mm = settleMonth.replaceAll("[^0-9]", "").substring(4);
        return mm.equals("03") || mm.equals("06") || mm.equals("09") || mm.equals("12");
    }

    /**
     * yyyyMM → 분기 문자열 (예: 202503 → 2025-Q1)
     * 03→Q1, 06→Q2, 09→Q3, 12→Q4
     */
    private String toQuarter(String settleMonth) {
        String digits = settleMonth.replaceAll("[^0-9]", "");
        String year = digits.substring(0, 4);
        String mm = digits.substring(4);
        String q;
        switch (mm) {
            case "03": q = "Q1"; break;
            case "06": q = "Q2"; break;
            case "09": q = "Q3"; break;
            default:   q = "Q4"; break;
        }
        return year + "-" + q;
    }
}
