package com.ga.batch.settlement.step;

import com.ga.batch.settlement.SettlementContext;
import com.ga.batch.settlement.transform.MappingEngine;
import com.ga.core.mapper.receive.ReceiveMapper;
import com.ga.core.vo.receive.RawCommissionDataVO;
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 2 — transformData: company_field_mapping + code_mapping 으로 표준 변환 → 원장 적재
 */
@Slf4j
@Component
@JobScope
@RequiredArgsConstructor
public class TransformDataStep implements Tasklet {

    private final SettlementContext ctx;
    private final ReceiveMapper receiveMapper;
    private final MappingEngine mappingEngine;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        log.info("[Step2 transformData] settleMonth={}", ctx.getSettleMonth());
        List<RawCommissionDataVO> raws = receiveMapper.selectRawList(null, ctx.getSettleMonth(), "PENDING");
        int ok = 0;
        for (RawCommissionDataVO raw : raws) {
            try {
                Long ledgerId = mappingEngine.transform(raw);
                receiveMapper.updateRawStatus(raw.getRawId(), "OK", ledgerId, raw.getMappedTable());
                ok++;
            } catch (Exception e) {
                log.warn("transform fail rawId={}: {}", raw.getRawId(), e.getMessage());
                receiveMapper.updateRawStatus(raw.getRawId(), "ERROR", null, null);
            }
        }
        ctx.setTransformedCount(ok);
        log.info("[Step2] transformed {} / {}", ok, raws.size());
        return RepeatStatus.FINISHED;
    }
}
