package com.its.op.service.its.ifsc;

import com.its.op.dao.repository.its.ifsc.TbIfscLinkRltnRepository;
import com.its.op.dto.its.ifsc.TbIfscLinkRltnDto;
import com.its.op.entity.its.ifsc.TbIfscRltnLink;
import com.its.op.entity.its.ifsc.TbIfscRltnLinkKey;
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 TbIfscLinkRltnService {

    private final TbIfscLinkRltnRepository repo;

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

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

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

    // 링크 구성정보 조회
    @Transactional(readOnly = true)
    public List<TbIfscLinkRltnDto> findLinkRltnById(Long ifscId) {
        List<TbIfscLinkRltnDto> result = new ArrayList<>();
        List<TbIfscRltnLink> data = this.repo.findLinkRltnById(ifscId);
        for (TbIfscRltnLink obj : data) {
            result.add(obj.toDto());
        }
        return result;
    }

    @Transactional
    protected boolean updateLinkRltnData(Long ifscId, List<TbIfscLinkRltnDto.TbIfscLinkRltnUpdReq> reqList) {
        // 기존 데이터를 모두 삭제
        this.repo.deleteDataById(ifscId);

        // 데이터 다시 입력
        for (TbIfscLinkRltnDto.TbIfscLinkRltnUpdReq req : reqList) {
            TbIfscRltnLink obj = req.toEntity(ifscId);
            this.repo.save(obj);
        }
        return true;
    }

    public List<TbIfscLinkRltnDto> updateLinkRltn(Long ifscId, List<TbIfscLinkRltnDto.TbIfscLinkRltnUpdReq> reqList) {
        updateLinkRltnData(ifscId, reqList);
        return findLinkRltnById(ifscId);
    }
}
