package com.its.op.service.its.link;

import com.its.op.dao.repository.its.link.TbLinkParaDetlRepository;
import com.its.op.dao.repository.its.link.TbLinkRepository;
import com.its.op.dto.its.link.LinkParaDetlDto;
import com.its.op.entity.its.link.TbLink;
import com.its.op.entity.its.link.TbLinkParaDetl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class LinkParaDetlService {

    private final TbLinkParaDetlRepository repo;
    private final TbLinkRepository linkRepo;

    public List<TbLinkParaDetl> findAll() {
        return this.repo.findAll();
    }

    public TbLinkParaDetl findById(Long id) {
        Optional<TbLinkParaDetl> data = this.repo.findById(id);
        if (data.isPresent()) {
            return data.get();
        }
        return null;
    }

    @Transactional
    public TbLinkParaDetl mergeById(Long id, LinkParaDetlDto.LinkParaDetlUpdateReq req) {
        Optional<TbLinkParaDetl> data = this.repo.findById(id);
        TbLinkParaDetl obj = data.orElseGet(() -> new TbLinkParaDetl(id));
        //obj.updateInfo(req);
        this.repo.save(obj);
        return obj;
    }

    @Transactional
    public LinkParaDetlDto.LinkParaDetlUpdateReq mergeAll(LinkParaDetlDto.LinkParaDetlUpdateReq req) {
        List<TbLink> links = this.linkRepo.findAll();
        for (TbLink link : links) {
            if (("Y").equals(link.getDelYn())) {
                continue;
            }

            Optional<TbLinkParaDetl> data = this.repo.findById(link.getLinkId());
            TbLinkParaDetl obj = data.orElseGet(() -> new TbLinkParaDetl(link.getLinkId()));
            //obj.updateInfo(req);
            this.repo.save(obj);
        }
        return req;
    }
}
