package com.ga.api.service.succession;

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.succession.ContractSuccessionMapper;
import com.ga.core.vo.succession.ContractSuccessionResp;
import com.ga.core.vo.succession.ContractSuccessionSaveReq;
import com.ga.core.vo.succession.ContractSuccessionSearchParam;
import com.ga.core.vo.succession.ContractSuccessionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

    private final ContractSuccessionMapper mapper;

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

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

    @Transactional
    public Long create(ContractSuccessionSaveReq req) {
        if (req.getFromAgentId().equals(req.getToAgentId())) {
            throw new BizException(ErrorCode.INVALID_PARAMETER, "전임과 후임 설계사가 같을 수 없습니다");
        }
        ContractSuccessionVO vo = new ContractSuccessionVO();
        vo.setContractId(req.getContractId());
        vo.setFromAgentId(req.getFromAgentId());
        vo.setToAgentId(req.getToAgentId());
        vo.setSuccessionDate(req.getSuccessionDate());
        vo.setReason(req.getReason());
        vo.setMemo(req.getMemo());
        vo.setCreatedBy(SecurityUtil.getCurrentUserId());
        mapper.insert(vo);
        return vo.getSuccessionId();
    }

    /** 승계 취소 — status=CANCELED. 이후 정산월부터 유지수수료는 다시 직전 귀속 설계사에게. */
    @Transactional
    public void cancel(Long successionId) {
        ContractSuccessionResp existing = mapper.selectById(successionId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.cancel(successionId, SecurityUtil.getCurrentUserId());
    }

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