package com.its.api.its.service.cctv;

import com.its.api.its.model.dto.cctv.TbCctvSttsHsDto;
import com.its.api.its.model.entity.cctv.TbCctvSttsHs;
import com.its.api.its.model.entity.cctv.TbCctvSttsHsKey;
import com.its.api.its.repository.cctv.TbCctvSttsHsRepository;
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 TbCctvSttsHsService {

    private final TbCctvSttsHsRepository repo;

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

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

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

    /**
     * 상태 이력 조회
     * @param fromDt
     * @param toDt
     * @param ids
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbCctvSttsHsDto> findAllByDateRange(String fromDt, String toDt, List<Long> ids) {

        List<TbCctvSttsHsDto> result = new ArrayList<>();
        List<TbCctvSttsHs> data = this.repo.findAllByDateRange(fromDt, toDt, ids);
        if (data != null) {
            data.forEach(obj -> {
                if (obj.getCctv() != null && ("N").equals(obj.getCctv().getDelYn())) {
                    result.add(obj.toDto());
                }
            });
        }
        return result;
    }

    /**
     * 장애 이력 조회
     * @param fromDt
     * @param toDt
     * @param ids
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbCctvSttsHsDto> findAllFailByDateRange(String fromDt, String toDt, List<Long> ids) {

        List<TbCctvSttsHsDto> result = new ArrayList<>();
        List<TbCctvSttsHs> data = this.repo.findAllFailByDateRange(fromDt, toDt, ids);
        if (data != null) {
            data.forEach(obj -> {
                if (obj.getCctv() != null && ("N").equals(obj.getCctv().getDelYn())) {
                    result.add(obj.toDto());
                }
            });
        }
        return result;
    }
}
