package com.its.api.its.service.vms;

import com.its.api.its.model.dto.vms.TbVmsFormObjectTypeDto;
import com.its.api.its.model.entity.vms.TbVmsFormObjectType;
import com.its.api.its.model.entity.vms.TbVmsFormObjectTypeKey;
import com.its.api.its.repository.vms.TbVmsFormObjectTypeRepository;
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 TbVmsFormObjectTypeService {

    private final TbVmsFormObjectTypeRepository repo;

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

    // 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbVmsFormObjectTypeDto> findAll() {
        List<TbVmsFormObjectTypeDto> result = new ArrayList<>();
        List<TbVmsFormObjectType> data = this.repo.findAll();
        data.forEach(obj -> {
            if (!("EDI2").equals(obj.getEdtnCd())) {
                result.add(obj.toDto());
            }
        });
        return result;
    }

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

    /**
     * 폼 유형별 객체 목록 조회
     * @param type
     * @return
     */
    public List<TbVmsFormObjectTypeDto> findAllByFormType(Integer type) {
        List<TbVmsFormObjectTypeDto> result = new ArrayList<>();
        List<TbVmsFormObjectType> data = this.repo.findAllByFormType(type);
        data.forEach(obj -> {
            if (!("EDI2").equals(obj.getEdtnCd())) {
                result.add(obj.toDto());
            }
        });
        return result;
    }
}
