package com.its.op.service.its.rse;

import com.its.op.dao.repository.its.rse.TbRseObuClctStatHhRepository;
import com.its.op.dto.its.rse.TbRseObuClctHsDto;
import com.its.op.dto.its.rse.TbRseObuClctStatHhDto;
import com.its.op.entity.its.rse.TbRseObuClctHs;
import com.its.op.entity.its.rse.TbRseObuClctStatHh;
import com.its.op.entity.its.rse.TbRseObuClctStatHhKey;
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 TbRseObuClctStatHhService {

    private final TbRseObuClctStatHhRepository repo;

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

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

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