package com.ga.batch.settlement.step;

import com.ga.batch.settlement.SettlementContext;
import com.ga.batch.settlement.receive.DataReceiver;
import com.ga.core.mapper.product.InsuranceCompanyMapper;
import com.ga.core.vo.product.InsuranceCompanyVO;
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.util.List;

/**
 * Step 1 — receiveData: 보험사별 DataReceiver 호출 → raw_commission_data 적재
 */
@Slf4j
@Component
@JobScope
@RequiredArgsConstructor
public class ReceiveDataStep implements Tasklet {

    private final SettlementContext ctx;
    private final InsuranceCompanyMapper companyMapper;
    private final List<DataReceiver> receivers;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        log.info("[Step1 receiveData] settleMonth={}", ctx.getSettleMonth());
        int total = 0;
        for (InsuranceCompanyVO c : companyMapper.selectActive()) {
            for (DataReceiver r : receivers) {
                if (r.supports(c.getCompanyCode())) {
                    int n = r.receive(c.getCompanyCode(), ctx.getSettleMonth());
                    log.info("  - {} via {}: {} rows", c.getCompanyCode(), r.getClass().getSimpleName(), n);
                    total += n;
                    break;
                }
            }
        }
        ctx.setReceivedCount(total);
        log.info("[Step1] received {} rows", total);
        return RepeatStatus.FINISHED;
    }
}
