package com.its.op.service.its.facility;

import com.its.op.dao.repository.its.facility.TbFcltSubjPartInRepository;
import com.its.op.dto.its.facility.TbFcltSubjPartDto;
import com.its.op.dto.its.facility.TbFcltSubjPartInDto;
import com.its.op.entity.its.facility.TbFcltSubjPartIn;
import com.its.op.entity.its.facility.TbFcltSubjPartInKey;
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 TbFcltSubjPartInService {

    private final TbFcltSubjPartInRepository repo;
    private final TbFcltSubjPartService partService;

    // 데이터 1건 조회, 없으면 exception
    private TbFcltSubjPartIn requireOne(TbFcltSubjPartInKey id) throws NoSuchElementException {
        Optional<TbFcltSubjPartIn> info = this.repo.findById(id);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + id);
        }
    }

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

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbFcltSubjPartInDto mergeInfo(TbFcltSubjPartInDto.TbFcltSubjPartInUpdReq req) {
        TbFcltSubjPartIn subjPart = null;
        try {
            TbFcltSubjPartInKey key = new TbFcltSubjPartInKey(req.getPartNmbr(), req.getInDt());
            subjPart = requireOne(key);
        } catch (Exception e) {
            log.info("New Data: {}", req);
        }
        int validCnt = req.getInCnt();
        if (subjPart != null) {
            validCnt -= subjPart.getInCnt();
        }
        TbFcltSubjPartDto part = this.partService.findById(req.getPartNmbr());
        part.setValidCnt(part.getValidCnt() + validCnt);

        req.setValidCnt(part.getValidCnt());
        TbFcltSubjPartIn obj = req.toEntity();
        this.repo.save(obj);

        if (validCnt != 0) {
            this.partService.updateValidCount(req.getPartNmbr(), part.getValidCnt());
        }
        return obj.toDto();
    }

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbFcltSubjPartInDto deleteById(TbFcltSubjPartInKey id) {
        TbFcltSubjPartIn entity = requireOne(id);

        this.repo.deleteById(id);

        TbFcltSubjPartDto part = this.partService.findById(id.getPartNmbr());
        int validCnt = part.getValidCnt() - entity.getInCnt();
        this.partService.updateValidCount(id.getPartNmbr(), validCnt);

        return entity.toDto();
    }

    @Transactional(readOnly = true)
    public List<TbFcltSubjPartInDto> findAllByPartNmbr(Long partNmbr) {
        List<TbFcltSubjPartInDto> result = new ArrayList<>();
        List<TbFcltSubjPartIn> data = this.repo.findAllByPartNmbr(partNmbr);
        for (TbFcltSubjPartIn entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    @Transactional(readOnly = true)
    public List<TbFcltSubjPartInDto> findAllByPartNmbrDateRange(Long partNmbr, String fromDay, String toDay) {
        List<TbFcltSubjPartInDto> result = new ArrayList<>();
        List<TbFcltSubjPartIn> data = this.repo.findAllByPartNmbrDateRange(partNmbr, fromDay, toDay);
        for (TbFcltSubjPartIn entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }
}
