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

import com.its.api.its.model.dto.vms.TbVmsCtrlHsDto;
import com.its.api.its.model.entity.vms.TbVmsCtrlHs;
import com.its.api.its.model.entity.vms.TbVmsCtrlHsKey;
import com.its.api.its.repository.vms.TbVmsCtrlHsRepository;
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 TbVmsCtrlHsService {

    private final TbVmsCtrlHsRepository repo;

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

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

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

    public List<TbVmsCtrlHsDto> findAllByDateRange(String fromDt, String toDt, List<Long> ids) {

        List<TbVmsCtrlHsDto> result = new ArrayList<>();
        List<TbVmsCtrlHs> data = this.repo.findAllByDateRange(fromDt, toDt, ids);
        if (data != null) {
            data.forEach(obj -> {
                result.add(obj.toDto());
            });
        }
        return result;
    }
}
