package com.ga.batch.settlement.step;

import com.ga.batch.settlement.SettlementContext;
import com.ga.core.mapper.income.AgentAnnualIncomeMapper;
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 9 (conditional) — yearEndIncomeAggregate: 연말 사업소득 집계
 *
 * 12월 마감 시에만 실행 (settleMonth ends with "-12" 또는 "12").
 * payment 테이블 기준으로 해당 연도 설계사별 SUM → agent_annual_income UPSERT.
 * SQL은 AgentAnnualIncomeMapper.upsertAggregate에 위임.
 */
@Slf4j
@Component
@JobScope
@RequiredArgsConstructor
public class YearEndIncomeAggregateStep implements Tasklet {

    private final SettlementContext ctx;
    private final AgentAnnualIncomeMapper incomeMapper;

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

        if (!isDecemberClose(settleMonth)) {
            log.info("[YearEndIncome] skipped — not a December close: {}", settleMonth);
            return RepeatStatus.FINISHED;
        }

        int year = extractYear(settleMonth);
        log.info("[YearEndIncome] aggregating income for year={}", year);

        int rows = incomeMapper.upsertAggregate(year);
        log.info("[YearEndIncome] agent_annual_income upserted: {} rows", rows);
        return RepeatStatus.FINISHED;
    }

    private boolean isDecemberClose(String settleMonth) {
        if (settleMonth == null) return false;
        // 형식: yyyyMM (예: 202512) 또는 yyyy-MM
        return settleMonth.endsWith("12");
    }

    private int extractYear(String settleMonth) {
        // yyyyMM → 앞 4자리
        String digits = settleMonth.replaceAll("[^0-9]", "");
        return Integer.parseInt(digits.substring(0, 4));
    }
}
