package com.its.op.service.its.code;

import com.its.op.dao.repository.its.code.TbClctSystStupRepository;
import com.its.op.dto.its.code.TbClctSystStupDto;
import com.its.op.entity.its.code.TbClctSystStup;
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 TbClctSystStupService {

    private final TbClctSystStupRepository repo;

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

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

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

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

}
