package com.its.op.service.its.road;

import com.its.op.dao.repository.its.road.TbRoadIfscRltnRepository;
import com.its.op.dto.its.road.TbRoadRltnIfscDto;
import com.its.op.entity.its.road.TbRoadRltnIfsc;
import com.its.op.entity.its.road.TbRoadRltnIfscKey;
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 TbRoadIfscRltnService {

    private final TbRoadIfscRltnRepository repo;

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

    // 데이터 변경
    /*public TbRoadIfscRltnDto updateById(TbRoadIfscRltnKey id, TbRoadIfscRltnDto.TbRoadIfscRltnUpdReq req) {
        TbRoadIfscRltn entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }*/

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

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

    // 정보제공구간 구성정보 조회
    @Transactional(readOnly = true)
    public List<TbRoadRltnIfscDto> findIfscRltnById(Long roadId) {
        List<TbRoadRltnIfscDto> result = new ArrayList<>();
        List<TbRoadRltnIfsc> data = this.repo.findIfscRltnById(roadId);
        for (TbRoadRltnIfsc obj : data) {
            result.add(obj.toDto());
        }
        return result;
    }

    @Transactional
    protected boolean updateIfscRltnData(Long roadId, List<TbRoadRltnIfscDto.TbRoadIfscRltnUpdReq> reqList) {
        // 기존 데이터를 모두 삭제
        this.repo.deleteDataById(roadId);

        // 데이터 다시 입력
        for (TbRoadRltnIfscDto.TbRoadIfscRltnUpdReq req : reqList) {
            TbRoadRltnIfsc obj = req.toEntity(roadId);
            this.repo.save(obj);
        }
        return true;
    }

    public List<TbRoadRltnIfscDto> updateIfscRltn(Long roadId, List<TbRoadRltnIfscDto.TbRoadIfscRltnUpdReq> reqList) {
        updateIfscRltnData(roadId, reqList);
        return findIfscRltnById(roadId);
    }
}
