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

import com.its.op.dao.repository.its.rse.TbRseCtlrCnncHsRepository;
import com.its.op.dto.its.rse.TbRseCtlrCnncHsDto;
import com.its.op.dto.its.rse.TbRseCtlrSttsHsDto;
import com.its.op.entity.its.rse.TbRseCtlrCnncHs;
import com.its.op.entity.its.rse.TbRseCtlrCnncHsKey;
import com.its.op.entity.its.rse.TbRseCtlrSttsHs;
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 TbRseCtlrCnncHsService {

    private final TbRseCtlrCnncHsRepository repo;

    // 데이터 1건 조회, 없으면 exception
    private TbRseCtlrCnncHs requireOne(TbRseCtlrCnncHsKey id) throws NoSuchElementException {
        Optional<TbRseCtlrCnncHs> 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<TbRseCtlrCnncHsDto> findAll() {
        List<TbRseCtlrCnncHsDto> result = new ArrayList<>();
        List<TbRseCtlrCnncHs> data = this.repo.findAll();
        for (TbRseCtlrCnncHs entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

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


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