package com.its.api.its.service.vds;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.code.VdsDtctTypeDto;
import com.its.api.its.model.dto.vds.TbVdsDtctDto;
import com.its.api.its.model.entity.code.TbCmmnCd;
import com.its.api.its.model.entity.vds.TbVdsDtct;
import com.its.api.its.model.entity.vds.TbVdsDtctLinkRltn;
import com.its.api.its.repository.code.TbCmmnCdRepository;
import com.its.api.its.repository.vds.TbVdsDtctLinkRltnRepository;
import com.its.api.its.repository.vds.TbVdsDtctRepository;
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.NoSuchElementException;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbVdsDtctService {

    private final TbVdsDtctRepository repo;
    private final TbVdsDtctLinkRltnRepository linkRltnRepo;
    private final TbCmmnCdRepository codeRepo;

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

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

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

    /**
     * 검지기 정보 업데이트
     * @param id
     * @param req
     * @return
     */
    @Transactional
    public TbVdsDtctDto updateById(String id, TbVdsDtctDto.TbVdsDtctMstrUpdReq req) {
        TbVdsDtct entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);

        TbVdsDtctLinkRltn linkRltn = new TbVdsDtctLinkRltn(req.getDtctNmbr(), req.getLinkId());
        this.linkRltnRepo.save(linkRltn);

        return entity.toDto();
    }

    /**
     * 검지기 정보 목록 저장
     * @param reqList
     * @return
     */
    @Transactional
    public List<TbVdsDtctDto> mergeInfoList(List<TbVdsDtctDto.TbVdsDtctMstrUpdReq> reqList) {
        List<TbVdsDtctDto> result = new ArrayList<>();
        for (TbVdsDtctDto.TbVdsDtctMstrUpdReq req : reqList) {
            TbVdsDtct obj = req.toEntity();
            this.repo.save(obj);

            TbVdsDtctLinkRltn linkRltn = new TbVdsDtctLinkRltn(req.getDtctNmbr(), req.getLinkId());
            this.linkRltnRepo.save(linkRltn);

            result.add(obj.toDto());
        }
        return result;
    }

    /**
     * 검지기 정보 저장
     * @param req
     * @return
     */
    @Transactional
    public TbVdsDtctDto mergeInfo(TbVdsDtctDto.TbVdsDtctMstrUpdReq req) {
        TbVdsDtct obj = req.toEntity();
        this.repo.save(obj);

        TbVdsDtctLinkRltn linkRltn = new TbVdsDtctLinkRltn(req.getDtctNmbr(), req.getLinkId());
        this.linkRltnRepo.save(linkRltn);
        return obj.toDto();
    }

    /**
     * 검지기 정보 개별 삭제
     * @param id
     * @return
     */
    @Transactional
    public TbVdsDtctDto deleteById(String id) {
        TbVdsDtct entity = requireOne(id);
        this.linkRltnRepo.deleteById(id);
        this.repo.deleteById(id);
        return entity.toDto();
    }

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

    /**
     * 검지기 유형(방향) 코드 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<VdsDtctTypeDto> findAllDtctType() {
        List<VdsDtctTypeDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.codeRepo.findAllByCmmnClsfCd(CodeManager.DTCT_TYPE_CD);
        data.forEach(obj -> {
            if (("Y").equals(obj.getUseYn())) {
                result.add(VdsDtctTypeDto.makeDto(obj));
            }
        });
        return result;
    }
}
