package com.caliverse.admin.domain.service;

import com.caliverse.admin.domain.dao.admin.ReqIdMapper;
import com.caliverse.admin.domain.entity.EReqType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReqIdService {
    private final ReqIdMapper reqIdMapper;

    @Transactional(transactionManager = "transactionManager")
    public Integer generateNextReqId(EReqType reqType, String createBy, String desc) {
        try {
            // 다음 REQ_ID 조회
            Integer nextReqId = reqIdMapper.getNextReqId(reqType.getValue());

            // 이력 저장
            reqIdMapper.insertReqIdHistory(reqType.getValue(), nextReqId, desc, createBy);

            log.debug("Generated REQ_ID: {} for type: {}", nextReqId, reqType.getValue());

            return nextReqId;

        } catch (Exception e) {
            log.error("Failed to generate REQ_ID for type: {}", reqType.getValue(), e);
            throw new RuntimeException("REQ_ID 생성 중 오류가 발생했습니다.", e);
        }
    }

    public List<Map<String, Object>> getRecentReqIdHistory(EReqType reqType, int limit) {
        return reqIdMapper.getReqIdHistory(reqType.getValue(), limit);
    }

    public Integer getCurrentMaxReqId(EReqType reqType) {
        Integer maxReqId = reqIdMapper.getNextReqId(reqType.getValue());
        return maxReqId != null ? maxReqId - 1 : 0; // 다음 ID에서 1을 빼면 현재 최대값
    }
}
