package com.erp.service;

import com.erp.common.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
public class DbTypeCategoryService extends BaseService {

    private static final String NS = "dbTypeCategory.";

    public List<Map<String, Object>> getAllCategories() {
        return sqlSession.selectList(NS + "selectAllCategories");
    }

    public Map<String, Object> getCategoryByTypeCode(String typeCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("type_code", typeCode);
        return sqlSession.selectOne(NS + "selectCategoryByTypeCode", params);
    }

    @Transactional
    public Map<String, Object> createCategory(Map<String, Object> params) {
        String typeCode = (String) params.get("type_code");

        Map<String, Object> checkParams = new HashMap<>();
        checkParams.put("type_code", typeCode);
        Integer existing = sqlSession.selectOne(NS + "countByTypeCode", checkParams);
        if (existing != null && existing > 0) {
            throw new IllegalArgumentException("이미 존재하는 DB 타입 코드입니다.");
        }

        sqlSession.insert(NS + "insertCategory", params);
        return sqlSession.selectOne(NS + "selectCategoryByTypeCode", checkParams);
    }

    @Transactional
    public Map<String, Object> updateCategory(String typeCode, Map<String, Object> params) {
        params.put("type_code", typeCode);
        sqlSession.update(NS + "updateCategory", params);

        Map<String, Object> checkParams = new HashMap<>();
        checkParams.put("type_code", typeCode);
        return sqlSession.selectOne(NS + "selectCategoryByTypeCode", checkParams);
    }

    @Transactional
    public void deleteCategory(String typeCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("type_code", typeCode);

        Integer connectionCount = sqlSession.selectOne(NS + "countConnectionsByType", params);
        if (connectionCount != null && connectionCount > 0) {
            throw new IllegalStateException(
                "해당 DB 타입을 사용하는 연결이 " + connectionCount + "개 있어 삭제할 수 없습니다.");
        }

        sqlSession.update(NS + "deactivateCategory", params);
    }

    public List<Map<String, Object>> getConnectionStatsByType() {
        return sqlSession.selectList(NS + "selectConnectionStatsByType");
    }

    @Transactional
    public void initializeDefaultCategories() {
        sqlSession.insert(NS + "insertDefaultCategories", null);
    }
}
