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

import com.its.op.dao.repository.its.rse.TbRseObuClctHsRepository;
import com.its.op.dto.its.rse.TbRseObuClctHsDto;
import com.its.op.entity.its.rse.TbRseObuClctHs;
import com.its.op.entity.its.rse.TbRseObuClctHsKey;
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 TbRseObuClctHsService {

    private final TbRseObuClctHsRepository repo;

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

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

    @Transactional(readOnly = true)
    public List<TbRseObuClctHsDto> findAllByDateRange(String fromDt, String toDt, String type, String kind, List<Long> ids) {
        List<TbRseObuClctHsDto> result = new ArrayList<>();
        List<TbRseObuClctHs> data = new ArrayList<>();
        if (type.equals("00") && !kind.equals("00")) {
            data = this.repo.findAllCtypByDateRange(fromDt, toDt, kind, ids);
        }
        else if (!type.equals("00") && kind.equals("00")) {
            data = this.repo.findAllKindByDateRange(fromDt, toDt, type, ids);
        }
        else if (type.equals("00") && kind.equals("00")) {
            data = this.repo.findAllByDateRange(fromDt, toDt, ids);
        }
        else {
            data = this.repo.findAllCKByDateRange(fromDt, toDt, type, kind, ids);
        }
        if (data != null) {
            data.forEach(obj -> {
                result.add(obj.toDto());
            });
        }
        return result;
    }
}
