package com.its.op.service.its.atrd;

import com.its.op.dao.repository.its.atrd.TbAtrdRoadRltnRepository;
import com.its.op.dto.its.atrd.TbAtrdRltnRoadDto;
import com.its.op.entity.its.atrd.TbAtrdRltnRoad;
import com.its.op.entity.its.atrd.TbAtrdRltnRoadKey;
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 TbAtrdRoadRltnService {

    private final TbAtrdRoadRltnRepository repo;

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

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbAtrdRltnRoadDto mergeInfo(String id, TbAtrdRltnRoadDto.TbAtrdRoadRltnUpdReq req) {
        TbAtrdRltnRoad obj = req.toEntity(id);
        this.repo.save(obj);
        return obj.toDto();
    }

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

    // 정보제공구간 구성정보 조회
    @Transactional(readOnly = true)
    public List<TbAtrdRltnRoadDto> findRoadRltnById(String atrdId) {
        List<TbAtrdRltnRoadDto> result = new ArrayList<>();
        List<TbAtrdRltnRoad> data = this.repo.findRoadRltnById(atrdId);
        for (TbAtrdRltnRoad obj : data) {
            result.add(obj.toDto());
        }
        return result;
    }
    // 정보제공구간 구성정보 조회
    @Transactional
    public void deleteDataById(String atrdId) {
        this.repo.deleteDataById(atrdId);
    }

    @Transactional
    public TbAtrdRltnRoad save(TbAtrdRltnRoad obj) {
        return this.repo.save(obj);
    }
}
