package com.ga.api.service.commission;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.util.DateUtil;
import com.ga.core.mapper.commission.ClawbackReceivableMapper;
import com.ga.core.mapper.commission.StatuteConfigMapper;
import com.ga.core.vo.commission.StatuteConfigResp;
import com.ga.core.vo.commission.StatuteConfigSaveReq;
import com.ga.core.vo.commission.StatuteConfigVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

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

    private final StatuteConfigMapper configMapper;
    private final ClawbackReceivableMapper receivableMapper;

    public List<StatuteConfigResp> listConfigs() {
        return configMapper.selectList();
    }

    public StatuteConfigResp detailConfig(Long configId) {
        StatuteConfigResp resp = configMapper.selectById(configId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long createConfig(StatuteConfigSaveReq req) {
        StatuteConfigVO vo = new StatuteConfigVO();
        vo.setEntityType(req.getEntityType());
        vo.setExpirationMonths(req.getExpirationMonths());
        vo.setIsActive(req.getIsActive() != null ? req.getIsActive() : "Y");
        configMapper.insert(vo);
        return vo.getConfigId();
    }

    @Transactional
    public void updateConfig(Long configId, StatuteConfigSaveReq req) {
        StatuteConfigResp resp = configMapper.selectById(configId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        StatuteConfigVO vo = new StatuteConfigVO();
        vo.setConfigId(configId);
        vo.setEntityType(req.getEntityType());
        vo.setExpirationMonths(req.getExpirationMonths());
        vo.setIsActive(req.getIsActive() != null ? req.getIsActive() : resp.getIsActive());
        configMapper.update(vo);
    }

    /**
     * 만료 대상 채권 일괄 대손 처리.
     * beforeMonth = baseMonth - expiration_months (YYYYMM 연산).
     * 처리 건수 반환.
     */
    @Transactional
    public int expireOverdue(String baseMonth) {
        StatuteConfigResp config = configMapper.selectByEntityType("CLAWBACK_RECEIVABLE");
        if (config == null || !"Y".equals(config.getIsActive())) {
            throw new BizException(ErrorCode.NOT_FOUND);
        }
        String beforeMonth = DateUtil.addMonth(baseMonth, -config.getExpirationMonths());
        return receivableMapper.writeOffExpired(beforeMonth, "EXPIRED");
    }
}
