package com.its.op.service.its.database;

import com.its.op.dao.repository.its.database.TbLeglHldyInfrRepository;
import com.its.op.dto.its.code.TbCmmnCdDto;
import com.its.op.dto.its.database.TbHldyInfrDto;
import com.its.op.entity.its.database.TbHldyInfr;
import com.its.op.global.CodeManager;
import com.its.op.service.its.code.TbCmmnCdService;
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 TbLeglHldyInfrService {

    private final TbLeglHldyInfrRepository repo;
    private final TbCmmnCdService cmmnCdService;

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

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

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

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

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

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

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

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

    // 휴일 유형 코드 목록 조회
    @Transactional(readOnly = true)
    public List<TbHldyInfrDto.LeglHldyType> findAllByLeglHldyType() {
        List<TbHldyInfrDto.LeglHldyType> result = new ArrayList<>();
        List<TbCmmnCdDto> data = this.cmmnCdService.findAllByCmmnClsfCd(CodeManager.HLDY_DAY_CD);
        if (data != null) {
	        data.forEach(obj -> {
	            if (("Y").equals(obj.getUseYn())) {
	                result.add(new TbHldyInfrDto.LeglHldyType(obj));
	            }
	        });
	    }
        return result;
    }
}
