package com.its.api.its.service.parking;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.common.FcltSttsSummaryDto;
import com.its.api.its.model.dto.common.FcltSttsDto;
import com.its.api.its.model.dto.common.FcltSttsListDto;
import com.its.api.its.model.dto.parking.ParkingLotDto;
import com.its.api.its.model.entity.parking.ParkingLot;
import com.its.api.its.repository.parking.ParkingLotRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class ParkingLotService {

    private final ParkingLotRepository repo;

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

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

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

    // 데이터 변경
    public ParkingLotDto updateById(String id, ParkingLotDto.ParkingLotUpdReq req) {
        ParkingLot entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

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

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

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

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

    /**
     * 상태 목록
     * @param
     */
    public FcltSttsListDto findAllSttsListTotal() {
        FcltSttsListDto result = new FcltSttsListDto();
        String fcltType = "PARK";

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<ParkingLot> ctlrList = this.repo.findAll();
        ctlrList.forEach(obj -> {
            FcltSttsDto stts = FcltSttsDto.builder()
                    .fcltType(fcltType)
                    .fcltNmbr(obj.getParkingId())
                    .fcltId(obj.getParkingId())
                    .fcltNm(obj.getParkingName())
                    .fcltKind("1")
                    .xCrdn(obj.getCoordx())
                    .yCrdn(obj.getCoordy())
                    .sttsCd(CodeManager.CMNC_STTS_NORMAL)
                    .sttsDesc("정상")
                    .build();

            sttsDtoList.add(stts);
        });

        FcltSttsSummaryDto summaryDto = FcltSttsSummaryDto.builder()
                .fcltType(fcltType)
                .fcltNm(fcltType)
                .totalCnt(ctlrList.size())
                .normalCnt(ctlrList.size())
                .errorCnt(0)
                .colErrCnt(0)
                .build();

        summaryDto.init();;
        summaryDto.setFcltObjs(sttsDtoList);

        result.getFcltList().add(summaryDto);

        return result;
    }

}
