package com.ga.api.service.commission;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.commission.LifeSupportLedgerMapper;
import com.ga.core.mapper.commission.LifeSupportRuleMapper;
import com.ga.core.vo.commission.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class LifeSupportService {

    private final LifeSupportRuleMapper ruleMapper;
    private final LifeSupportLedgerMapper ledgerMapper;

    // ── Rule ──────────────────────────────────────────────────────────────────

    public PageResponse<LifeSupportRuleResp> listRules(LifeSupportRuleSearchParam param) {
        param.startPage();
        return PageResponse.of(ruleMapper.selectList(param));
    }

    public LifeSupportRuleResp detailRule(Long ruleId) {
        LifeSupportRuleResp resp = ruleMapper.selectById(ruleId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long createRule(LifeSupportRuleSaveReq req) {
        LifeSupportRuleVO vo = new LifeSupportRuleVO();
        vo.setAgentGrade(req.getAgentGrade());
        vo.setSupportRate(req.getSupportRate());
        vo.setEffectiveFrom(req.getEffectiveFrom());
        vo.setEffectiveTo(req.getEffectiveTo());
        ruleMapper.insert(vo);
        return vo.getRuleId();
    }

    @Transactional
    public void updateRule(Long ruleId, LifeSupportRuleSaveReq req) {
        LifeSupportRuleResp resp = ruleMapper.selectById(ruleId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        LifeSupportRuleVO vo = new LifeSupportRuleVO();
        vo.setRuleId(ruleId);
        vo.setAgentGrade(req.getAgentGrade());
        vo.setSupportRate(req.getSupportRate());
        vo.setEffectiveFrom(req.getEffectiveFrom());
        vo.setEffectiveTo(req.getEffectiveTo());
        ruleMapper.update(vo);
    }

    @Transactional
    public void deleteRule(Long ruleId) {
        LifeSupportRuleResp resp = ruleMapper.selectById(ruleId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        ruleMapper.delete(ruleId);
    }

    // ── Ledger ────────────────────────────────────────────────────────────────

    public PageResponse<LifeSupportLedgerResp> listLedgers(LifeSupportLedgerSearchParam param) {
        param.startPage();
        return PageResponse.of(ledgerMapper.selectList(param));
    }

    public LifeSupportLedgerResp detailLedger(Long ledgerId) {
        LifeSupportLedgerResp resp = ledgerMapper.selectById(ledgerId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long createLedger(LifeSupportLedgerSaveReq req) {
        // 지원수수료 = base × support_rate
        BigDecimal supportAmount = req.getBaseAmount()
                .multiply(req.getSupportRate())
                .setScale(2, RoundingMode.HALF_UP);
        BigDecimal clawback = req.getClawbackAmount() != null ? req.getClawbackAmount() : BigDecimal.ZERO;
        // 환수액은 음수 불가, 지원수수료 초과 불가 (net 음수 방지)
        if (clawback.signum() < 0 || clawback.compareTo(supportAmount) > 0) {
            throw new BizException(ErrorCode.BAD_REQUEST,
                    String.format("환수액(%s)은 0 이상이며 지원수수료(%s)를 초과할 수 없습니다",
                            clawback, supportAmount));
        }
        // 실지급액 = support - clawback
        BigDecimal netAmount = supportAmount.subtract(clawback).setScale(2, RoundingMode.HALF_UP);

        LifeSupportLedgerVO vo = new LifeSupportLedgerVO();
        vo.setAgentId(req.getAgentId());
        vo.setSettleMonth(req.getSettleMonth());
        vo.setBaseAmount(req.getBaseAmount());
        vo.setSupportRate(req.getSupportRate());
        vo.setSupportAmount(supportAmount);
        vo.setClawbackAmount(clawback);
        vo.setNetAmount(netAmount);
        vo.setStatus("CALCULATED");
        ledgerMapper.insert(vo);
        return vo.getLedgerId();
    }
}
