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

import com.its.api.its.model.dto.vms.TbVmsDsplPrstDto;
import com.its.api.its.model.entity.vms.TbVmsDsplPrst;
import com.its.api.its.model.entity.vms.TbVmsDsplPrstKey;
import com.its.api.its.repository.vms.TbVmsDsplPrstRepository;
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 TbVmsDsplPrstService {

    private final TbVmsDsplPrstRepository repo;

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

    /**
     * 현재 표출 VMS 메시지 전체 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsDsplPrstDto> findAll() {
        List<TbVmsDsplPrstDto> result = new ArrayList<>();
        List<TbVmsDsplPrst> data = this.repo.findAll();
        for (TbVmsDsplPrst entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

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

    /**
     * 현재 표출 VMS 메시지 개별 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsDsplPrstDto> findAllByIds(List<Long> id) {
        List<TbVmsDsplPrstDto> result = new ArrayList<>();
        List<TbVmsDsplPrst> data = this.repo.findAllByIds(id);
        for (TbVmsDsplPrst entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 관리번호, 표출번호에 해당하는 메시지 조회
     * @param vmsCtlrNmbr
     * @param phase
     * @return
     */
    @Transactional(readOnly = true)
    public TbVmsDsplPrstDto findAllByIdAndPhase(Long vmsCtlrNmbr, Integer phase) {
        TbVmsDsplPrstKey key = new TbVmsDsplPrstKey(vmsCtlrNmbr, phase);
        TbVmsDsplPrst result = requireOne(key);
        return result.toDto();
/*
        List<TbVmsDsplPrst> data = this.repo.findAllByIdAndPhase(vmsCtlrNmbr, phase);
        if (!data.isEmpty()) {
            return data.get(0).toDto();
        }
        return null;
*/
    }
}
