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.DataDomainMapper;
import com.ga.core.vo.dict.DataDomainOptionResp;
import com.ga.core.vo.dict.DataDomainResp;
import com.ga.core.vo.dict.DataDomainSaveReq;
import com.ga.core.vo.dict.DataDomainSearchParam;
import com.ga.core.vo.dict.DataDomainVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DataDomainService {

    private final DataDomainMapper mapper;

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

    public List<DataDomainOptionResp> options() {
        return mapper.selectAll();
    }

    public DataDomainResp detail(String domainCode) {
        DataDomainResp resp = mapper.selectByCode(domainCode);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public void create(DataDomainSaveReq req) {
        if (mapper.selectByCode(req.getDomainCode()) != null) {
            throw new BizException(ErrorCode.DUPLICATE_DATA, "이미 존재하는 도메인 코드입니다");
        }
        mapper.insert(req.toVO());
    }

    @Transactional
    public void update(String domainCode, DataDomainSaveReq req) {
        if (mapper.selectByCode(domainCode) == null) {
            throw new BizException(ErrorCode.NOT_FOUND);
        }
        DataDomainVO vo = req.toVO();
        vo.setDomainCode(domainCode);
        mapper.update(vo);
    }

    @Transactional
    public void delete(String domainCode) {
        int usageCount = mapper.countUsageByCode(domainCode);
        if (usageCount > 0) {
            throw new BizException(ErrorCode.DEPENDENT_DATA,
                    "이 도메인을 사용하는 컬럼이 " + usageCount + "개 있습니다");
        }
        if (mapper.delete(domainCode) == 0) {
            throw new BizException(ErrorCode.NOT_FOUND);
        }
    }
}
