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

import com.its.api.its.model.dto.link.LinkParaDetlDto;
import com.its.api.its.model.entity.link.TbLinkParaDetl;
import com.its.api.its.model.entity.link.TbLink;
import com.its.api.its.repository.link.TbLinkParaDetlRepository;
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 LinkParaDetlService {

    private final TbLinkParaDetlRepository repo;
    private final TbLinkRepository linkRepo;

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

    public TbLinkParaDetl findById(Long id) {
        try {
            Optional<TbLinkParaDetl> 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 TbLinkParaDetl mergeById(Long id, LinkParaDetlDto.LinkParaDetlUpdateReq req) {
        try {
            Optional<TbLinkParaDetl> data = this.repo.findById(id);
            TbLinkParaDetl obj = data.orElseGet(() -> new TbLinkParaDetl(id));
            obj.updateInfo(req);
            this.repo.save(obj);
            return obj;
        }
        catch (Exception e) {
            log.error("{}.mergeById: Object: {}, Exception: {}", getClass().getSimpleName(), req, e.getMessage());
        }
        return null;
    }

    @Transactional
    public LinkParaDetlDto.LinkParaDetlUpdateReq mergeAll(LinkParaDetlDto.LinkParaDetlUpdateReq req) {
        try {
            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);
            }
        }
        catch (Exception e) {
            log.error("{}.mergeAll: Object: {}, Exception: {}", getClass().getSimpleName(), req, e.getMessage());
        }
        return req;
    }
}
