package com.ga.batch.settlement.domain;

import com.ga.core.mapper.installment.InstallmentRatioMapper;
import com.ga.core.vo.installment.InstallmentPlanVO;
import com.ga.core.vo.installment.InstallmentRatioVO;
import com.ga.core.vo.installment.InstallmentStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 배치용 분급 계획 생성기. ga-api InstallmentPlanGenerator와 동일 로직.
 * 계약 체결일 기준 1~7차년 분급 계획 생성.
 */
@Component
@RequiredArgsConstructor
public class BatchInstallmentPlanGenerator {

    private static final DateTimeFormatter DATE_FMT  = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter MONTH_FMT = DateTimeFormatter.ofPattern("yyyyMM");

    private final InstallmentRatioMapper ratioMapper;

    public List<InstallmentPlanVO> generate(Long contractId, BigDecimal totalCommission,
                                            LocalDate contractDate, String productCategory) {
        String baseDate = contractDate.format(DATE_FMT);
        List<InstallmentRatioVO> ratios = ratioMapper.selectAllActiveRatios(productCategory, baseDate);

        List<InstallmentPlanVO> plans = new ArrayList<>();
        for (InstallmentRatioVO ratio : ratios) {
            InstallmentPlanVO plan = new InstallmentPlanVO();
            plan.setContractId(contractId);
            plan.setPlanYear(ratio.getPlanYear());
            plan.setPlanMonth(1);
            plan.setSettleMonth(contractDate.plusYears(ratio.getPlanYear()).format(MONTH_FMT));
            plan.setExpectedAmount(
                    totalCommission.multiply(ratio.getRatioPercent())
                                   .divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP)
            );
            plan.setStatus(InstallmentStatus.SCHEDULED.code());
            plans.add(plan);
        }
        return plans;
    }
}
