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.common.util.SecurityUtil;
import com.ga.core.mapper.commission.ChargebackWaiverRequestMapper;
import com.ga.core.vo.commission.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

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

    private final ChargebackWaiverRequestMapper mapper;

    public PageResponse<ChargebackWaiverRequestResp> list(ChargebackWaiverRequestSearchParam param) {
        param.startPage();
        return PageResponse.of(mapper.selectList(param));
    }

    public ChargebackWaiverRequestResp detail(Long requestId) {
        ChargebackWaiverRequestResp resp = mapper.selectById(requestId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    /**
     * 감면 신청 등록 — waiver_amount <= original_chargeback 검증.
     */
    @Transactional
    public Long create(ChargebackWaiverRequestSaveReq req) {
        if (req.getWaiverAmount().compareTo(req.getOriginalChargeback()) > 0) {
            throw new BizException(ErrorCode.INVALID_PARAMETER);
        }
        ChargebackWaiverRequestVO vo = new ChargebackWaiverRequestVO();
        vo.setContractId(req.getContractId());
        vo.setAgentId(req.getAgentId());
        vo.setSettleMonth(req.getSettleMonth());
        vo.setOriginalChargeback(req.getOriginalChargeback());
        vo.setWaiverAmount(req.getWaiverAmount());
        vo.setReason(req.getReason());
        vo.setApprovalStatus("REQUESTED");
        vo.setCreatedBy(SecurityUtil.getCurrentUserId());
        mapper.insert(vo);
        return vo.getRequestId();
    }

    /**
     * 승인 처리 — approval_status = APPROVED, approver_id = 현재 사용자, approved_at = now.
     */
    @Transactional
    public void approve(Long requestId) {
        ChargebackWaiverRequestResp resp = mapper.selectById(requestId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        if (!"REQUESTED".equals(resp.getApprovalStatus())) throw new BizException(ErrorCode.INVALID_PARAMETER);
        mapper.updateApproval(requestId, "APPROVED", SecurityUtil.getCurrentUserId(), LocalDateTime.now());
    }

    /**
     * 반려 처리 — approval_status = REJECTED.
     */
    @Transactional
    public void reject(Long requestId) {
        ChargebackWaiverRequestResp resp = mapper.selectById(requestId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        if (!"REQUESTED".equals(resp.getApprovalStatus())) throw new BizException(ErrorCode.INVALID_PARAMETER);
        mapper.updateApproval(requestId, "REJECTED", SecurityUtil.getCurrentUserId(), LocalDateTime.now());
    }
}
