/*
 * Licensed to Open Source Radio Access Network(OS-RAN) Alliance and OAI
 * Software Alliance under one or more contributor license agreements. The
 * initial OpenXG series projects are derided from OAI projects, the files from
 * OAI projects are all in compliance with OAI Public License, Version 1.1.
 * codes and files developed from OpenXG projects and from OS-RAN Alliance
 * are all under OS-RAN licenses; you may not use this file except in compliance
 * with the license.  You may get a copy of the license at:
 *	http://www.openxg.org.cn/?falu_69.html
 * For more information about OpenXG, please contact:
 * contact@openxg.org.cn
 */

#include "SubscriptionsCollectionApiImpl.h"

#include "logger.hpp"
#include "smf_msg.hpp"
#include "3gpp_29.508.h"
#include "itti_msg_sbi.hpp"
#include "smf_config.hpp"
#include "3gpp_conversions.hpp"

extern smf::smf_config smf_cfg;

namespace oai {
namespace smf_server {
namespace api {

using namespace oai::smf_server::model;

SubscriptionsCollectionApiImpl::SubscriptionsCollectionApiImpl(
    std::shared_ptr<Pistache::Rest::Router> rtr, smf::smf_app* smf_app_inst,
    std::string address)
    : SubscriptionsCollectionApi(rtr),
      m_smf_app(smf_app_inst),
      m_address(address) {}

void SubscriptionsCollectionApiImpl::create_individual_subcription(
    const NsmfEventExposure& nsmfEventExposure,
    Pistache::Http::ResponseWriter& response) {
  Logger::smf_api_server().info(
      "SubscriptionsCollectionApiImpl::create_individual_subcription...");

  // Create a  message and store the necessary information
  Logger::smf_api_server().debug(
      "Create a Event Exposure message and store the necessary information");
  smf::event_exposure_msg event_exposure = {};

  // Convert from NsmfEventExposure to event_exposure_msg
  xgpp_conv::smf_event_exposure_notification_from_openapi(
      nsmfEventExposure, event_exposure);

  // Handle the message in smf_app
  std::shared_ptr<itti_sbi_event_exposure_request> itti_msg =
      std::make_shared<itti_sbi_event_exposure_request>(
          TASK_SMF_SBI, TASK_SMF_APP);
  itti_msg->event_exposure = event_exposure;
  itti_msg->http_version   = 1;

  evsub_id_t sub_id = m_smf_app->handle_event_exposure_subscription(itti_msg);

  // Send response
  nlohmann::json json_data = {};
  to_json(json_data, nsmfEventExposure);

  if (sub_id != -1) {
    json_data["subId"] = std::to_string(sub_id);
    response.headers().add<Pistache::Http::Header::Location>(
        m_address + base + smf_cfg.sbi_api_version + "/nsmf_event-exposure/" +
        std::to_string(sub_id));  // Location header
  }

  response.headers().add<Pistache::Http::Header::ContentType>(
      Pistache::Http::Mime::MediaType("application/json"));
  response.send(Pistache::Http::Code(201), json_data.dump().c_str());
}

}  // namespace api
}  // namespace smf_server
}  // namespace oai
