package com.ga.api.service.product;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.product.ContractMapper;
import com.ga.core.mapstruct.ContractMapStruct;
import com.ga.core.vo.product.ContractResp;
import com.ga.core.vo.product.ContractSaveReq;
import com.ga.core.vo.product.ContractSearchParam;
import com.ga.core.vo.product.ContractStatus;
import com.ga.core.vo.product.ContractVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ContractService {

    private final ContractMapper mapper;
    private final ContractMapStruct contractMapStruct;

    @Transactional(readOnly = true)
    public PageResponse<ContractResp> list(ContractSearchParam param) {
        param.startPage();
        return PageResponse.of(mapper.selectList(param));
    }

    @Transactional(readOnly = true)
    public ContractResp detail(Long contractId) {
        ContractResp resp = mapper.selectDetailById(contractId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long create(ContractSaveReq req) {
        if (mapper.existsByPolicyNo(req.getPolicyNo()) > 0) {
            throw new BizException(ErrorCode.DUPLICATE_DATA, "이미 등록된 증권번호입니다");
        }
        ContractVO vo = contractMapStruct.toVO(req);
        vo.setStatus(ContractStatus.ACTIVE.name());
        mapper.insert(vo);
        return vo.getContractId();
    }

    @Transactional
    public void update(Long contractId, ContractSaveReq req) {
        ContractVO vo = mapper.selectById(contractId);
        if (vo == null) throw new BizException(ErrorCode.NOT_FOUND);
        contractMapStruct.updateVO(req, vo);
        mapper.update(vo);
    }

    @Transactional
    public void changeStatus(Long contractId, String status) {
        mapper.updateStatus(contractId, status);
    }
}
