package com.its.op.service.its.vms;

import com.its.op.dao.repository.its.vms.TbVmsIfscRltnIfscRepository;
import com.its.op.dto.its.vms.TbVmsIfscRltnIfscDto;
import com.its.op.entity.its.vms.TbVmsIfscRltnIfsc;
import com.its.op.entity.its.vms.TbVmsIfscRltnIfscKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbVmsIfscRltnIfscService {

    private final TbVmsIfscRltnIfscRepository repo;

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

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

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

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

    // VMS_IFSC_ID 사용 중인 갯수 리턴
    public int findUsageCountByVmsIfscId(Long vmsIfscId ) {
        return this.repo.findUsageCountByVmsIfscId(vmsIfscId);
    }

    public List<TbVmsIfscRltnIfscDto> findDataById(Long id) {
        List<TbVmsIfscRltnIfscDto> result = new ArrayList<>();
        List<TbVmsIfscRltnIfsc> list = this.repo.findDataById(id);
        for (TbVmsIfscRltnIfsc obj : list) {
            if (obj.getIfsc() != null && ("N").equals(obj.getIfsc().getDelYn())) {
                // 삭제 된것 제외
                TbVmsIfscRltnIfscDto dto = obj.toDto();
                dto.setIfscInfo(obj.getIfsc()); // 정보제공구간 정보 설정
                result.add(dto);
            }
        }
        return result;
    }

    public void deleteDataById(Long id) {
        this.repo.deleteDataById(id);
    }
}
