package com.ga.api.service.settle;

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.settle.CarrierReconciliationOutMapper;
import com.ga.core.vo.settle.CarrierReconciliationOutResp;
import com.ga.core.vo.settle.CarrierReconciliationOutSaveReq;
import com.ga.core.vo.settle.CarrierReconciliationOutSearchParam;
import com.ga.core.vo.settle.CarrierReconciliationOutVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

    private final CarrierReconciliationOutMapper reconOutMapper;

    public PageResponse<CarrierReconciliationOutResp> list(CarrierReconciliationOutSearchParam param) {
        param.startPage();
        return PageResponse.of(reconOutMapper.selectList(param));
    }

    public CarrierReconciliationOutResp detail(Long reconOutId) {
        CarrierReconciliationOutResp resp = reconOutMapper.selectById(reconOutId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long create(CarrierReconciliationOutSaveReq req) {
        // 보험사+정산월 중복 확인
        CarrierReconciliationOutVO existing = reconOutMapper.selectByCarrierMonth(req.getCarrierId(), req.getSettleMonth());
        if (existing != null) {
            throw new BizException(ErrorCode.DUPLICATE_DATA,
                    "이미 등록된 회신 이력입니다: carrierId=" + req.getCarrierId() + ", settleMonth=" + req.getSettleMonth());
        }

        CarrierReconciliationOutVO vo = new CarrierReconciliationOutVO();
        vo.setCarrierId(req.getCarrierId());
        vo.setSettleMonth(req.getSettleMonth());
        vo.setFilePath(req.getFilePath());
        vo.setFileName(req.getFileName());
        vo.setFileSize(req.getFileSize());
        vo.setRecordCount(req.getRecordCount());
        vo.setStatus("READY");
        vo.setRetryCount(0);
        vo.setCreatedBy(SecurityUtil.getCurrentUserId());
        reconOutMapper.insert(vo);
        return vo.getReconOutId();
    }

    @Transactional
    public void retry(Long reconOutId) {
        CarrierReconciliationOutVO vo = reconOutMapper.selectVoById(reconOutId);
        if (vo == null) throw new BizException(ErrorCode.NOT_FOUND);
        if (!"FAIL".equals(vo.getStatus())) {
            throw new BizException(ErrorCode.INVALID_STATUS, "실패 상태만 재전송 가능합니다");
        }
        // 상태를 READY로 초기화하여 배치가 재처리
        reconOutMapper.updateStatus(reconOutId, "READY");
    }
}
