package com.ga.api.service.endorse;

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

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

    private final ContractEndorsementMapper mapper;

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

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

    @Transactional
    public Long create(ContractEndorsementSaveReq req) {
        ContractEndorsementVO vo = new ContractEndorsementVO();
        vo.setContractId(req.getContractId());
        vo.setAgentId(req.getAgentId());
        vo.setEndorsementType(req.getEndorsementType());
        vo.setOldValue(req.getOldValue());
        vo.setNewValue(req.getNewValue());
        vo.setReason(req.getReason());
        vo.setRequiresCommissionRecalc(req.getRequiresCommissionRecalc());
        vo.setProcessed(false);
        mapper.insert(vo);
        return vo.getEndorsementId();
    }

    /**
     * 수동 처리 완료 표시 — 실제 수수료 재계산은 배치 담당(P5).
     * status 변경(processed=true) 만 수행.
     */
    @Transactional
    public void process(Long endorsementId) {
        ContractEndorsementResp existing = mapper.selectById(endorsementId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.markProcessed(endorsementId);
    }

    @Transactional
    public void delete(Long endorsementId) {
        ContractEndorsementResp existing = mapper.selectById(endorsementId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.delete(endorsementId);
    }
}
