package com.its.op.service.its.facility;

import com.its.op.dao.repository.its.facility.TbFcltFailOcrrTypeRepository;
import com.its.op.dto.its.facility.TbFcltFailOcrrTypeDto;
import com.its.op.entity.its.facility.TbFcltFailOcrrType;
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 TbFcltFailOcrrTypeService {

    private final TbFcltFailOcrrTypeRepository repo;

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

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

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

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbFcltFailOcrrTypeDto mergeInfo(TbFcltFailOcrrTypeDto.TbFcltFailOcrrTypeUpdReq req) {
        TbFcltFailOcrrType obj = req.toEntity();
        this.repo.save(obj);
        return obj.toDto();
    }

}
