package com.kamco.cd.kamcoback.Innopam.postgres.core;

import com.kamco.cd.kamcoback.Innopam.dto.DetectMastDto;
import com.kamco.cd.kamcoback.Innopam.dto.DetectMastDto.Basic;
import com.kamco.cd.kamcoback.Innopam.dto.DetectMastDto.DetectMastReq;
import com.kamco.cd.kamcoback.Innopam.dto.DetectMastDto.DetectMastSearch;
import com.kamco.cd.kamcoback.Innopam.postgres.entity.DetectMastEntity;
import com.kamco.cd.kamcoback.Innopam.postgres.repository.DetectMastRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class DetectMastCoreService {

  private final DetectMastRepository detectMastRepository;

  public void saveDetectMast(DetectMastReq detectMast) {
    DetectMastEntity detectMastEntity = new DetectMastEntity();
    detectMastEntity.setCprsBfYr(detectMast.getCprsBfYr());
    detectMastEntity.setCprsAdYr(detectMast.getCprsAdYr());
    detectMastEntity.setDtctSno(detectMast.getDtctSno());
    detectMastEntity.setPathNm(detectMast.getPathNm());
    detectMastEntity.setCrtEpno(detectMast.getCrtEpno());
    detectMastEntity.setCrtIp(detectMast.getCrtIp());
    detectMastRepository.save(detectMastEntity);
  }

  public List<Basic> selectDetectMast(DetectMastSearch detectMast) {
    return detectMastRepository.findDetectMastList(detectMast).stream()
        .map(
            e ->
                new DetectMastDto.Basic(
                    e.getId(),
                    e.getCprsBfYr(),
                    e.getCprsAdYr(),
                    e.getDtctSno(),
                    e.getPathNm(),
                    e.getCrtEpno(),
                    e.getCrtIp()))
        .toList();
  }

  public Basic selectDetectMast(Long id) {
    DetectMastEntity e =
        detectMastRepository.findById(id).orElseThrow(() -> new RuntimeException("등록 데이터가 없습니다."));
    return new DetectMastDto.Basic(
        e.getId(),
        e.getCprsBfYr(),
        e.getCprsAdYr(),
        e.getDtctSno(),
        e.getPathNm(),
        e.getCrtEpno(),
        e.getCrtIp());
  }

  public String findPnuData(DetectMastSearch detectMast) {
    DetectMastEntity detectMastEntity = detectMastRepository.findPnuData(detectMast);
    return detectMastEntity.getPathNm();
  }
}
