package com.ga.api.service.statement;

import com.ga.core.mapper.settle.PaymentMapper;
import com.ga.core.vo.settle.PaymentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
@RequiredArgsConstructor
public class StatementAggregator {

    private final PaymentMapper paymentMapper;

    public StatementSummary aggregate(Long agentId, String settleMonth) {
        List<PaymentVO> payments = paymentMapper.selectByAgentAndMonth(agentId, settleMonth);

        BigDecimal grossAmount    = sum(payments, PaymentVO::getPayAmount);
        BigDecimal incomeTax      = sum(payments, PaymentVO::getIncomeTaxAmount);
        BigDecimal localTax       = sum(payments, PaymentVO::getLocalTaxAmount);
        BigDecimal vat            = sum(payments, PaymentVO::getVatAmount);
        BigDecimal deduction      = sum(payments, PaymentVO::getDeductionAmount);
        BigDecimal netAmount      = sum(payments, PaymentVO::getNetAmount);

        return new StatementSummary(grossAmount, incomeTax, localTax, vat, deduction, netAmount);
    }

    private BigDecimal sum(List<PaymentVO> payments, java.util.function.Function<PaymentVO, BigDecimal> getter) {
        return payments.stream()
                .map(p -> getter.apply(p) != null ? getter.apply(p) : BigDecimal.ZERO)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
