package com.its.op.service.its.code;

import com.its.op.dao.repository.its.code.TbCmmnCdRepository;
import com.its.op.dao.repository.its.code.TbCmmnClsfCdRepository;
import com.its.op.dto.its.code.FcltTypeDto;
import com.its.op.dto.its.code.TbCmmnCdDto;
import com.its.op.entity.its.code.TbCmmnCd;
import com.its.op.entity.its.code.TbCmmnCdKey;
import com.its.op.global.CodeManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbCmmnCdService {

    private final TbCmmnCdRepository repo;
    private final TbCmmnClsfCdRepository clsfCdRepository;

    // 데이터 1건 조회, 없으면 exception
    private TbCmmnCd requireOne(TbCmmnCdKey id) throws NoSuchElementException {
        Optional<TbCmmnCd> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
//        return repo.findById(id)
//                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

    // 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbCmmnCdDto> findAll() {
        List<TbCmmnCdDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.repo.findAll();
        for (TbCmmnCd entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    // 데이터 변경 또는 생성-목록(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public List<TbCmmnCdDto> mergeInfoList(List<TbCmmnCdDto.TbCmmnCdUpdReq> reqList) {
        List<TbCmmnCdDto> result = new ArrayList<>();
        for (TbCmmnCdDto.TbCmmnCdUpdReq req : reqList) {
            TbCmmnCd obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbCmmnCdDto mergeInfo(TbCmmnCdDto.TbCmmnCdUpdReq req) {
        TbCmmnCd obj = req.toEntity();
        this.repo.save(obj);
        return obj.toDto();
    }

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbCmmnCdDto deleteById(String cmmnClsfCd, String cmmnCd) {
        TbCmmnCdKey key = new TbCmmnCdKey(cmmnCd, cmmnClsfCd);
        TbCmmnCd entity = requireOne(key);
        this.repo.deleteById(key);
        return entity.toDto();
    }

    // 정보 삭제-목록, 존재하는 데이터 만 삭제
    @Transactional
    public List<TbCmmnCdDto> deleteByIds(List<TbCmmnCdKey> ids) {
        List<TbCmmnCdDto> result = new ArrayList<>();
        for (TbCmmnCdKey id : ids) {
            Optional<TbCmmnCd> obj = this.repo.findById(id);
            if (obj.isPresent()) {
                this.repo.deleteById(id);
                result.add(obj.get().toDto());
            }
        }
        return result;
    }

    // 세부 코드 목록 조회
    @Transactional
    public List<TbCmmnCdDto> findAllByCmmnClsfCd(String cmmnClsfCd) {
        List<TbCmmnCdDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.repo.findAllByCmmnClsfCd(cmmnClsfCd);
        for (TbCmmnCd entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 시설물 유형 코드 목롲 조회
     */
    @Transactional(readOnly = true)
    public List<FcltTypeDto> selectAllFcltType() {
        List<FcltTypeDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.repo.findAllByCmmnClsfCd(CodeManager.FCLT_TYPE_CD);
        if (data != null) {
            data.forEach(obj -> {
                if (("Y").equals(obj.getUseYn())) {
                    result.add(FcltTypeDto.makeDto(obj));
                }
            });
        }
        return result;
    }
}
