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

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.facility.FcltFailTypeDto;
import com.its.api.its.model.dto.facility.TbFcltFailHsDto;
import com.its.api.its.model.entity.code.TbCmmnCd;
import com.its.api.its.model.entity.facility.TbFcltFailHs;
import com.its.api.its.repository.code.TbCmmnCdRepository;
import com.its.api.its.repository.facility.TbFcltFailHsRepository;
import com.its.api.its.repository.facility.TbFcltFailRparHsRepository;
import com.its.api.utils.ItsUtils;
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 TbFcltFailHsService {

    private final TbFcltFailHsRepository repo;
    private final TbFcltFailRparHsRepository rparHsRepo;
    private final TbCmmnCdRepository cmmnCdRepo;

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

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

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

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

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

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

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

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

    /**
     * 시설물 ID에 해당하는 장애 내용 목록을 조회
     * @param fcltId
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbFcltFailHsDto> findAllFailList(String fcltId) {

        List<TbFcltFailHsDto> result = new ArrayList<>();
        List<TbFcltFailHs> data = this.repo.findAllFailList(fcltId);
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    /**
     * 시설물 장애이력 신규 ID 조회
     * @param
     * @return
     */
    @Transactional(readOnly = true)
    public String findNewHsSeq() {
        String currYear = ItsUtils.getSysTime("yyyyMM");
        Integer newId =  this.repo.findNewHsSeq(currYear);
        return String.format("%s%04d", currYear, newId);
    }

    /**
     * 시설물 장애 유형 코드 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<FcltFailTypeDto> findAllFailType() {

        List<FcltFailTypeDto> result = new ArrayList<>();
        List<TbCmmnCd> data = this.cmmnCdRepo.findAllByCmmnClsfCd(CodeManager.FCLT_FAIL_TYPE_CD);
        if (data != null) {
            data.forEach(obj -> {
                if (("Y").equals(obj.getUseYn())) {
                    result.add(FcltFailTypeDto.makeDto(obj));
                }
            });
        }

        return result;
    }
}
