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

import com.its.op.dao.repository.its.oper.TbOperSystMenuRepository;
import com.its.op.dto.its.oper.TbOperSystMenuDto;
import com.its.op.entity.its.oper.TbOperSystMenu;
import com.its.op.entity.its.oper.TbOperSystMenuKey;
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 TbUserOperSystMenuService {

    private final TbOperSystMenuRepository repo;

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

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

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

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

}
