package com.ga.api.service.tax;

import com.ga.common.system.SystemConfigService;
import com.ga.core.vo.org.TaxType;
import com.ga.core.vo.org.VatType;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Component
@RequiredArgsConstructor
public class TaxCalculator {

    private final SystemConfigService configService;

    public TaxBreakdown calculate(BigDecimal amount, TaxType taxType, VatType vatType) {
        // 음수/0 정산(환수 우위 등)은 원천징수 대상이 아님 → 세금 0, net=원금(차월 이월).
        if (amount == null || amount.signum() <= 0) {
            BigDecimal base = amount != null ? amount : BigDecimal.ZERO;
            return new TaxBreakdown(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, base);
        }

        BigDecimal incomeRate = resolveIncomeRate(taxType);
        BigDecimal localRate  = configService.getDecimal("TAX_RATE_LOCAL_INCOME", new BigDecimal("10.0"));
        BigDecimal vatRate    = configService.getDecimal("TAX_RATE_VAT", new BigDecimal("10.0"));

        BigDecimal incomeTax = amount.multiply(incomeRate)
                .divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP);
        BigDecimal localTax = incomeTax.multiply(localRate)
                .divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP);
        BigDecimal vat = VatType.TAXABLE.equals(vatType)
                ? amount.multiply(vatRate).divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP)
                : BigDecimal.ZERO;
        BigDecimal netAmount = amount.subtract(incomeTax).subtract(localTax).add(vat);

        return new TaxBreakdown(incomeTax, localTax, vat, netAmount);
    }

    private BigDecimal resolveIncomeRate(TaxType taxType) {
        if (TaxType.OTHER_INCOME.equals(taxType)) {
            return configService.getDecimal("TAX_RATE_OTHER_INCOME", new BigDecimal("8.8"));
        }
        return configService.getDecimal("TAX_RATE_BUSINESS_INCOME", new BigDecimal("3.3"));
    }
}
