package com.its.api.its.service.vms;

import com.its.api.its.model.dto.common.TrafDto;
import com.its.api.its.model.dto.vms.TbVmsCmtrInfrDto;
import com.its.api.its.model.entity.vms.TbVmsCmtrInfr;
import com.its.api.its.repository.vms.TbVmsCmtrInfrRepository;
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 TbVmsCmtrInfrService {

    private final TbVmsCmtrInfrRepository repo;

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

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

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

    /**
     * 소통정보조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TrafDto> findAllTraf() {
        List<TrafDto> result = new ArrayList<>();
        List<TbVmsCmtrInfr> data = this.repo.findAll();
        data.forEach(obj -> {
            result.add(obj.toTrafDto());
        });
        return result;
    }

    /**
     * VMS 제어기별 VMS 정보제공구간 소통정보 조회
     * @param id
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsCmtrInfrDto> findAllTrafByVms(Long id) {
        List<TbVmsCmtrInfrDto> result = new ArrayList<>();
        List<TbVmsCmtrInfr> data = this.repo.findAllByVms(id);
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }
}
