package com.its.api.its.service.link;

import com.its.api.its.model.dto.link.TbLinkVrtxArrDto;
import com.its.api.its.model.entity.link.TbLinkVrtxArr;
import com.its.api.its.model.entity.link.TbLinkVrtxArrKey;
import com.its.api.its.repository.link.TbLinkVrtxArrRepository;
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;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbLinkVrtxArrService {

    private final TbLinkVrtxArrRepository repo;

    // 데이터 1건 조회, 없으면 exception
    private TbLinkVrtxArr requireOne(TbLinkVrtxArrKey id) {
        return this.repo.findById(id)
                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

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

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbLinkVrtxArrDto findById(TbLinkVrtxArrKey id) {
        TbLinkVrtxArr entity = requireOne(id);
        return entity.toDto();
    }

    /**
     * 레벨에 따른 버텍스 정보 조회
     * @param levl
     * @return
     */
    public List<TbLinkVrtxArrDto> findAllByLevl(Integer levl) {
        List<TbLinkVrtxArrDto> result = new ArrayList<>();
        List<TbLinkVrtxArr> data = this.repo.findAllByLevl(levl);
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }
}
