package com.its.op.service.its.oper;

import com.its.op.dao.repository.its.oper.TbUserGropInfrRepository;
import com.its.op.dto.its.oper.TbUserGropInfrDto;
import com.its.op.entity.its.oper.TbUserGropInfr;
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.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbUserGropInfrService {

    private final TbUserGropInfrRepository repo;

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

    // 데이터 변경 또는 생성-목록(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public List<TbUserGropInfrDto> mergeInfoList(List<TbUserGropInfrDto.TbUserGropInfrUpdReq> reqList) {
        List<TbUserGropInfrDto> result = new ArrayList<>();
        for (TbUserGropInfrDto.TbUserGropInfrUpdReq req : reqList) {
            TbUserGropInfr obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

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

    // 정보 삭제-목록, 존재하는 데이터 만 삭제
    @Transactional
    public List<TbUserGropInfrDto> deleteByIds(List<String> ids) {
        List<TbUserGropInfrDto> result = new ArrayList<>();
        for (String id : ids) {
            Optional<TbUserGropInfr> obj = this.repo.findById(id);
            if (obj.isPresent()) {
                this.repo.deleteById(id);
                result.add(obj.get().toDto());
            }
        }
        return result;
    }

    // 유효한 사용자 그룹 정보 조회
    @Transactional(readOnly = true)
    public List<TbUserGropInfrDto> findAllUserGropInfr() {
        List<TbUserGropInfrDto> result = new ArrayList<>();
        List<TbUserGropInfr> data = this.repo.findAll();
        if (data != null) {
	        data.forEach(obj -> {
	            if (("N").equals(obj.getDelYn())) {
	                result.add(obj.toDto());
	            }
	        });
	    }
        return result;
    }
}
