package com.ga.batch.settlement.domain;

import com.ga.core.mapper.chargeback.ChargebackGradeMapper;
import com.ga.core.vo.chargeback.ChargebackGradeVO;
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.time.temporal.ChronoUnit;

/**
 * 배치용 차등환수 계산기. ga-api ChargebackCalculator와 동일 로직.
 * chargeback_grade 테이블 기반 5단계 환수율 조회.
 */
@Component
@RequiredArgsConstructor
public class BatchChargebackCalculator {

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

    private final ChargebackGradeMapper gradeMapper;

    public ChargebackResult calculate(LocalDate contractDate, LocalDate terminationDate,
                                      BigDecimal originalCommission, String productCategory) {
        int monthsElapsed = (int) ChronoUnit.MONTHS.between(contractDate, terminationDate);
        String today = LocalDate.now().format(DATE_FMT);

        ChargebackGradeVO grade = gradeMapper.selectByMonths(productCategory, monthsElapsed, today);

        if (grade == null) {
            return new ChargebackResult(BigDecimal.ZERO, monthsElapsed, BigDecimal.ZERO,
                    "적용 환수 구간 없음");
        }

        BigDecimal chargebackAmount = originalCommission
                .multiply(grade.getChargebackPercent())
                .divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP);

        return new ChargebackResult(
                chargebackAmount,
                monthsElapsed,
                grade.getChargebackPercent(),
                String.format("경과월 %d개월 → 환수율 %s%%", monthsElapsed, grade.getChargebackPercent())
        );
    }
}
