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.AgentGuaranteeInsuranceMapper;
import com.ga.core.vo.commission.AgentGuaranteeInsuranceResp;
import com.ga.core.vo.commission.AgentGuaranteeInsuranceSaveReq;
import com.ga.core.vo.commission.AgentGuaranteeInsuranceSearchParam;
import com.ga.core.vo.commission.AgentGuaranteeInsuranceVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

    private final AgentGuaranteeInsuranceMapper guaranteeInsuranceMapper;

    public PageResponse<AgentGuaranteeInsuranceResp> list(AgentGuaranteeInsuranceSearchParam param) {
        param.startPage();
        return PageResponse.of(guaranteeInsuranceMapper.selectList(param));
    }

    public AgentGuaranteeInsuranceResp detail(Long guaranteeId) {
        AgentGuaranteeInsuranceResp resp = guaranteeInsuranceMapper.selectById(guaranteeId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long create(AgentGuaranteeInsuranceSaveReq req) {
        AgentGuaranteeInsuranceVO vo = new AgentGuaranteeInsuranceVO();
        vo.setAgentId(req.getAgentId());
        vo.setPolicyNo(req.getPolicyNo());
        vo.setCarrierId(req.getCarrierId());
        vo.setGuaranteeAmount(req.getGuaranteeAmount());
        vo.setStartDate(req.getStartDate());
        vo.setEndDate(req.getEndDate());
        vo.setStatus("ACTIVE");
        guaranteeInsuranceMapper.insert(vo);
        return vo.getGuaranteeId();
    }

    @Transactional
    public void update(Long guaranteeId, AgentGuaranteeInsuranceSaveReq req) {
        AgentGuaranteeInsuranceResp resp = guaranteeInsuranceMapper.selectById(guaranteeId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        AgentGuaranteeInsuranceVO vo = new AgentGuaranteeInsuranceVO();
        vo.setGuaranteeId(guaranteeId);
        vo.setAgentId(req.getAgentId());
        vo.setPolicyNo(req.getPolicyNo());
        vo.setCarrierId(req.getCarrierId());
        vo.setGuaranteeAmount(req.getGuaranteeAmount());
        vo.setStartDate(req.getStartDate());
        vo.setEndDate(req.getEndDate());
        guaranteeInsuranceMapper.update(vo);
    }

    @Transactional
    public void delete(Long guaranteeId) {
        AgentGuaranteeInsuranceResp resp = guaranteeInsuranceMapper.selectById(guaranteeId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        guaranteeInsuranceMapper.delete(guaranteeId);
    }
}
