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.common.util.SecurityUtil;
import com.ga.core.mapper.commission.StepCloseMapper;
import com.ga.core.vo.commission.StepCloseResp;
import com.ga.core.vo.commission.StepCloseSaveReq;
import com.ga.core.vo.commission.StepCloseSearchParam;
import com.ga.core.vo.commission.StepCloseVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

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

    private final StepCloseMapper stepCloseMapper;

    public PageResponse<StepCloseResp> list(StepCloseSearchParam param) {
        param.startPage();
        return PageResponse.of(stepCloseMapper.selectList(param));
    }

    public List<StepCloseResp> listByMonth(String settleMonth) {
        return stepCloseMapper.selectBySettleMonth(settleMonth);
    }

    public StepCloseResp detail(Long stepCloseId) {
        StepCloseResp resp = stepCloseMapper.selectById(stepCloseId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long create(StepCloseSaveReq req) {
        StepCloseVO vo = new StepCloseVO();
        vo.setSettleMonth(req.getSettleMonth());
        vo.setStepCode(req.getStepCode());
        vo.setStepSeq(req.getStepSeq());
        vo.setStatus("OPEN");
        stepCloseMapper.insert(vo);
        return vo.getStepCloseId();
    }

    @Transactional
    public void close(Long stepCloseId) {
        StepCloseResp resp = stepCloseMapper.selectById(stepCloseId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        if ("CLOSED".equals(resp.getStatus())) {
            throw new BizException(ErrorCode.INVALID_STATUS, "이미 마감된 단계입니다.");
        }
        stepCloseMapper.updateStatus(stepCloseId, "CLOSED", SecurityUtil.getCurrentUserId());
    }

    @Transactional
    public void reopen(Long stepCloseId) {
        StepCloseResp resp = stepCloseMapper.selectById(stepCloseId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        if ("OPEN".equals(resp.getStatus())) {
            throw new BizException(ErrorCode.INVALID_STATUS, "이미 열려 있는 단계입니다.");
        }
        stepCloseMapper.updateStatus(stepCloseId, "OPEN", SecurityUtil.getCurrentUserId());
    }
}
