package com.its.api.its.service.link;

import com.its.api.its.model.dto.link.LinkParaStupDto;
import com.its.api.its.model.entity.link.TbLinkParaStup;
import com.its.api.its.model.entity.link.TbLink;
import com.its.api.its.repository.link.TbLinkParaStupRepository;
import com.its.api.its.repository.link.TbLinkRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@RequiredArgsConstructor
@Service
public class LinkParaStupService {

    private final TbLinkParaStupRepository repo;
    private final TbLinkRepository linkRepo;

    public List<TbLinkParaStup> findAll() {
        try {
            return this.repo.findAll();
        }
        catch (Exception e) {
            log.error("{}.findAll: Exception: {}", getClass().getSimpleName(), e.getMessage());
        }
        return new ArrayList<>();
    }

    public TbLinkParaStup findById(Long id) {
        try {
            Optional<TbLinkParaStup> data = this.repo.findById(id);
            if (data.isPresent()) {
                return data.get();
            }
        }
        catch (Exception e) {
            log.error("{}.findById: Object: {}, Exception: {}", getClass().getSimpleName(), id, e.getMessage());
        }
        return null;
    }

    @Transactional
    public TbLinkParaStup mergeById(Long id, LinkParaStupDto.LinkParaStupUpdateReq req) {
        try {
            Optional<TbLinkParaStup> data = this.repo.findById(id);
            TbLinkParaStup obj = data.orElseGet(() -> new TbLinkParaStup(id));
            obj.updateInfo(req);
            this.repo.save(obj);
            return obj;
        }
        catch (Exception e) {
            log.error("{}.mergeInfo: Object: {}, Exception: {}", getClass().getSimpleName(), req, e.getMessage());
        }
        return null;
    }

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

                Optional<TbLinkParaStup> data = this.repo.findById(link.getLinkId());
                TbLinkParaStup obj = data.orElseGet(() -> new TbLinkParaStup(link.getLinkId()));
                obj.updateInfo(req);
                this.repo.save(obj);
            }
        }
        catch (Exception e) {
            log.error("{}.mergeAll: Object: {}, Exception: {}", getClass().getSimpleName(), req, e.getMessage());
        }
        return req;
    }
}
