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

import com.its.op.dao.repository.its.facility.TbFcltSubjPartOutRepository;
import com.its.op.dto.its.facility.TbFcltSubjPartDto;
import com.its.op.dto.its.facility.TbFcltSubjPartOutDto;
import com.its.op.entity.its.facility.TbFcltSubjPartOut;
import com.its.op.entity.its.facility.TbFcltSubjPartOutKey;
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 TbFcltSubjPartOutService {

    private final TbFcltSubjPartOutRepository repo;
    private final TbFcltSubjPartService partService;

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

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

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    @Transactional
    public TbFcltSubjPartOutDto mergeInfo(TbFcltSubjPartOutDto.TbFcltSubjPartOutUpdReq req) {

        TbFcltSubjPartOut subjPart = null;
        try {
            TbFcltSubjPartOutKey key = new TbFcltSubjPartOutKey(req.getPartNmbr(), req.getFcltId(), req.getOutDt());
            subjPart = requireOne(key);
        } catch (Exception e) {
            log.info("New Data: {}", req);
        }
        int validCnt = req.getOutCnt();
        if (subjPart != null) {
            validCnt -= subjPart.getOutCnt();
        }

        TbFcltSubjPartDto part = this.partService.findById(req.getPartNmbr());
        part.setValidCnt(part.getValidCnt() - validCnt);

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

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

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    @Transactional
    public TbFcltSubjPartOutDto deleteById(TbFcltSubjPartOutKey id) {
        TbFcltSubjPartOut entity = requireOne(id);
        this.repo.deleteById(id);

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

        return entity.toDto();
    }

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

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

}
