package com.its.api.its.service.facility;

import com.its.api.its.model.dto.cctv.TbCctvCtlrDto;
import com.its.api.its.model.dto.facility.TbFcltInfrDto;
import com.its.api.its.model.dto.facility.UnRegisteredFcltInfrDto;
import com.its.api.its.model.dto.vds.TbVdsCtlrDto;
import com.its.api.its.model.dto.vms.TbVmsCtlrDto;
import com.its.api.its.model.entity.facility.TbFcltInfr;
import com.its.api.its.repository.facility.TbFcltInfrRepository;
import com.its.api.its.service.cctv.TbCctvCtlrService;
import com.its.api.its.service.vds.TbVdsCtlrService;
import com.its.api.its.service.vms.TbVmsCtlrService;
import com.its.api.utis.model.dto.RsemstDto;
import com.its.api.utis.service.RsemstService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbFcltInfrService {

    private final TbFcltInfrRepository repo;
    private final TbVmsCtlrService vmsCtlrService;
    private final TbVdsCtlrService vdsCtlrService;
    private final TbCctvCtlrService cctvCtlrService;
    private final RsemstService rseMstService;

    // 데이터 1건 조회, 없으면 exception
    private TbFcltInfr requireOne(String id) {
        return this.repo.findById(id)
                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

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

    /**
     * 삭제되지 않은 시설물 정보 전체 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbFcltInfrDto> findAllList() {
        List<TbFcltInfrDto> result = new ArrayList<>();
        List<TbFcltInfr> data = this.repo.findAllList();
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbFcltInfrDto findById(String id) {
        TbFcltInfr entity = requireOne(id);
        return entity.toDto();
    }

    // 데이터 변경
    @Transactional
    public TbFcltInfrDto updateById(String id, TbFcltInfrDto.TbFcltInfrUpdReq req) {
        TbFcltInfr entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

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

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

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbFcltInfrDto deleteById(String id) {
        TbFcltInfr entity = requireOne(id);
        this.repo.deleteById(id);
        return entity.toDto();
    }

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

    /**
     * 미등록 시설물 정보 등록
     * @param listReq
     * @return
     */
    @Transactional
    public List<TbFcltInfrDto> mergeRegInfoList(List<UnRegisteredFcltInfrDto.TbRegFcltInfrUpdReq> listReq) {
        List<TbFcltInfrDto> result = new ArrayList<>();
        listReq.forEach(obj -> {
            TbFcltInfr entity = obj.toEntity();
            this.repo.save(entity);
            result.add(entity.toDto());
        });
        return result;
    }

    /**
     * 미등록 시설물 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<UnRegisteredFcltInfrDto> findAllUnRegisteredList() {
        List<UnRegisteredFcltInfrDto> result = new ArrayList<>();
        Map<String, TbFcltInfrDto> regMap = new HashMap<>();
        List<TbFcltInfrDto> regList = findAllList();
        regList.forEach(obj -> {
            regMap.put(obj.getFcltId(), obj);
        });

        List<TbVmsCtlrDto> vmsList = this.vmsCtlrService.findAllList();
        vmsList.forEach(obj -> {
            TbFcltInfrDto regObj = regMap.get(obj.getVmsCtlrId());
            if (regObj == null) {
                result.add(UnRegisteredFcltInfrDto.builder()
                        .fcltType("VMS")
                        .fcltId(obj.getVmsCtlrId())
                        .fcltLctn(obj.getVmsNm())
                        .build());
            }
        });

        List<TbVdsCtlrDto> vdsList = this.vdsCtlrService.findAllList();
        vdsList.forEach(obj -> {
            TbFcltInfrDto regObj = regMap.get(obj.getVdsCtlrId());
            if (regObj == null) {
                result.add(UnRegisteredFcltInfrDto.builder()
                        .fcltType("VDS")
                        .fcltId(obj.getVdsCtlrId())
                        .fcltLctn(obj.getLctn())
                        .build());
            }
        });

        List<TbCctvCtlrDto> cctvList = this.cctvCtlrService.findAllList();
        cctvList.forEach(obj -> {
            TbFcltInfrDto regObj = regMap.get(obj.getCctvCtlrId());
            if (regObj == null) {
                result.add(UnRegisteredFcltInfrDto.builder()
                        .fcltType("CCTV")
                        .fcltId(obj.getCctvCtlrId())
                        .fcltLctn(obj.getIstlLctnNm())
                        .build());
            }
        });

        List<RsemstDto> rseList = this.rseMstService.findAllList();
        rseList.forEach(obj -> {
            TbFcltInfrDto regObj = regMap.get(obj.getRseid());
            if (regObj == null) {
                result.add(UnRegisteredFcltInfrDto.builder()
                        .fcltType("RSE")
                        .fcltId(obj.getRseid())
                        .fcltLctn(obj.getLocation())
                        .build());
            }
        });

        return result;
    }
}
