package com.interplug.qcast.biz.canvaspopupstatus;

import com.interplug.qcast.biz.canvaspopupstatus.dto.CanvasPopupStatus;
import com.interplug.qcast.config.Exception.ErrorCode;
import com.interplug.qcast.config.Exception.QcastException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CanvasPopupStatusService {

  private final CanvasPopupStatusMapper canvasPopupStatusMapper;

  /**
   * Canvas Popup Status 조회
   *
   * @param objectNo 조회할 object 번호
   * @param planNo 조회할 plan 번호
   * @param popupType 조회할 popup 타입
   * @return 조회된 CanvasPopupStatus 객체, 조회된 데이터가 없을 경우 빈 객체 반환
   */
  public CanvasPopupStatus selectCanvasPopupStatus(
      String objectNo, Integer planNo, String popupType) throws QcastException {
    CanvasPopupStatus request =
        CanvasPopupStatus.builder().objectNo(objectNo).planNo(planNo).popupType(popupType).build();
    CanvasPopupStatus cps = canvasPopupStatusMapper.selectCanvasPopupStatus(request);
    return cps != null ? cps : CanvasPopupStatus.builder().build();
  }

  /**
   * Canvas Popup Status 저장 - 이미 존재하는 데이터인 경우 수정, 없는 경우 생성
   *
   * @param cps 저장할 CanvasPopupStatus 객체
   * @throws QcastException 저장 중 예외 발생 시
   */
  @Transactional
  public void saveCanvasPopupStatus(CanvasPopupStatus cps) throws QcastException {
    CanvasPopupStatus chk = canvasPopupStatusMapper.selectCanvasPopupStatus(cps);
    if (chk == null) {
      createCanvasPopupStatus(cps);
    } else {
      updateCanvasPopupStatus(cps);
    }
  }

  /**
   * Canvas Popup Status 생성
   *
   * @param cps 생성할 CanvasPopupStatus 객체
   * @throws QcastException 생성 중 예외 발생 시
   */
  @Transactional
  public void createCanvasPopupStatus(CanvasPopupStatus cps) throws QcastException {
    try {
      canvasPopupStatusMapper.insertCanvasPopupStatus(cps);
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  /**
   * Canvas Popup Status 수정
   *
   * @param cps 수정할 CanvasPopupStatus 객체
   * @throws QcastException 수정 중 예외 발생 시
   */
  public void updateCanvasPopupStatus(CanvasPopupStatus cps) throws QcastException {
    try {
      canvasPopupStatusMapper.updateCanvasPopupStatus(cps);
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  /**
   * Canvas Popup Status 삭제
   *
   * @param cps 삭제할 CanvasPopupStatus 객체
   * @throws QcastException 삭제 중 예외 발생 시
   */
  public void deleteCanvasPopupStatus(CanvasPopupStatus cps) throws QcastException {
    try {
      canvasPopupStatusMapper.deleteCanvasPopupStatus(cps);
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }
}
