package com.ga.api.service.dict;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.dict.DataDictionaryMapper;
import com.ga.core.vo.dict.DataDictionaryFullResp;
import com.ga.core.vo.dict.DataDictionaryResp;
import com.ga.core.vo.dict.DataDictionarySaveReq;
import com.ga.core.vo.dict.DataDictionarySearchParam;
import com.ga.core.vo.dict.DataDictionaryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DataDictionaryService {

    private final DataDictionaryMapper mapper;

    public PageResponse<DataDictionaryResp> list(DataDictionarySearchParam param) {
        param.startPage();
        return PageResponse.of(mapper.selectList(param));
    }

    public List<String> tables() {
        return mapper.selectTables();
    }

    public List<DataDictionaryFullResp> full(String tableName) {
        return mapper.selectFromView(tableName);
    }

    public DataDictionaryResp detail(Long dictId) {
        DataDictionaryResp resp = mapper.selectById(dictId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public void create(DataDictionarySaveReq req) {
        if (req.getDomainCode() != null && !req.getDomainCode().isBlank()) {
            if (mapper.countDomainByCode(req.getDomainCode()) == 0) {
                throw new BizException(ErrorCode.NOT_FOUND, "존재하지 않는 도메인 코드입니다: " + req.getDomainCode());
            }
        }
        mapper.insert(req.toVO());
    }

    @Transactional
    public void update(Long dictId, DataDictionarySaveReq req) {
        DataDictionaryResp existing = mapper.selectById(dictId);
        if (existing == null) throw new BizException(ErrorCode.NOT_FOUND);
        if (req.getDomainCode() != null && !req.getDomainCode().isBlank()) {
            if (mapper.countDomainByCode(req.getDomainCode()) == 0) {
                throw new BizException(ErrorCode.NOT_FOUND, "존재하지 않는 도메인 코드입니다: " + req.getDomainCode());
            }
        }
        DataDictionaryVO vo = req.toVO();
        vo.setDictId(dictId);
        mapper.update(vo);
    }

    @Transactional
    public void delete(Long dictId) {
        if (mapper.delete(dictId) == 0) {
            throw new BizException(ErrorCode.NOT_FOUND);
        }
    }
}
