package com.interplug.qcast.biz.canvasSetting;

import com.interplug.qcast.biz.canvasSetting.dto.CanvasSettingInfo;
import com.interplug.qcast.config.Exception.ErrorCode;
import com.interplug.qcast.config.Exception.QcastException;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CanvasSettingService {
  private final CanvasSettingMapper canvasSettingMapper;

  // Canvas Setting 조회(objectNo)
  public CanvasSettingInfo selectCanvasSetting(String objectNo) throws QcastException {
    try {
      return canvasSettingMapper.selectCanvasSetting(objectNo);
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }

  // Canvas Setting 등록
  public Map<String, String> insertCanvasSetting(CanvasSettingInfo csi) throws QcastException {

    Map<String, String> response = new HashMap<>();

    if (csi.getObjectNo() == null) {
      throw new QcastException(ErrorCode.INVALID_INPUT_VALUE, "올바르지 않은 입력값입니다.");
    }

    try {

      // 먼저 데이터가 존재하는지 확인
      CanvasSettingInfo cntData = canvasSettingMapper.getCanvasSettingCnt(csi.getObjectNo());

      // 데이터가 존재하지 않으면 insert
      if (cntData.getCnt().intValue() < 1) {
        canvasSettingMapper.insertCanvasSetting(csi);
      } else {
        canvasSettingMapper.updateCanvasSetting(csi);
      }
      response.put("objectNo", csi.getObjectNo());
      response.put("returnMessage", "common.message.confirm.mark");
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    // 생성된 objectNo 반환
    return response;
  }

  // Canvas Setting 수정
  public void updateCanvasSetting(CanvasSettingInfo csi) throws QcastException {
    try {
      canvasSettingMapper.updateCanvasSetting(csi);
    } catch (Exception e) {
      throw new QcastException(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }
}
