/*
  This file is part of TALER
  Copyright (C) 2025 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1, or (at your option) any later version.

  TALER is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with TALER; see the file COPYING.LGPL.
  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file merchant_api_post-private-categories.c
 * @brief Implementation of POST /private/categories
 * @author Bohdan Potuzhnyi
 */
#include "taler/platform.h"
#include <curl/curl.h>
#include <jansson.h>
#include <microhttpd.h>
#include <gnunet/gnunet_util_lib.h>
#include "taler/taler_merchant_service.h"
#include "merchant_api_curl_defaults.h"
#include "merchant_api_common.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_curl_lib.h>

/**
 * Handle for a POST /private/categories operation.
 */
struct TALER_MERCHANT_CategoriesPostHandle
{
  /**
   * Fully qualified request URL.
   */
  char *url;

  /**
   * CURL job handle.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Callback to invoke with the result.
   */
  TALER_MERCHANT_CategoriesPostCallback cb;

  /**
   * Closure for @a cb.
   */
  void *cb_cls;

  /**
   * Execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
   * Helper keeping POST body and headers alive.
   */
  struct TALER_CURL_PostContext post_ctx;
};

/**
 * Called when the HTTP transfer finishes.
 *
 * @param cls operation handle
 * @param response_code HTTP status (0 on network / parsing failures)
 * @param response parsed JSON reply (NULL if unavailable)
 */
static void
handle_post_categories_finished (void *cls,
                                 long response_code,
                                 const void *response)
{
  struct TALER_MERCHANT_CategoriesPostHandle *cph = cls;
  const json_t *json = response;
  struct TALER_MERCHANT_CategoriesPostResponse cpr = {
    .hr.http_status = (unsigned int) response_code,
    .hr.reply = json
  };

  cph->job = NULL;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "POST /private/categories completed with status %u\n",
              (unsigned int) response_code);
  switch (response_code)
  {
  case MHD_HTTP_OK:
    {
      const char *err_name;
      unsigned int err_line;
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_uint64 ("category_id",
                                 &cpr.category_id),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (json,
                             spec,
                             &err_name,
                             &err_line))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Invalid response for field %s\n",
                    err_name);
        cpr.hr.http_status = 0;
        cpr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
      }
      break;
    }
  case MHD_HTTP_BAD_REQUEST:
  case MHD_HTTP_UNAUTHORIZED:
  case MHD_HTTP_FORBIDDEN:
  case MHD_HTTP_NOT_FOUND:
  case MHD_HTTP_CONFLICT:
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    cpr.hr.ec = TALER_JSON_get_error_code (json);
    cpr.hr.hint = TALER_JSON_get_error_hint (json);
    break;
  case 0:
    cpr.hr.ec = TALER_EC_GENERIC_INVALID_RESPONSE;
    break;
  default:
    TALER_MERCHANT_parse_error_details_ (json,
                                         response_code,
                                         &cpr.hr);
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response %u/%d for POST /private/categories\n",
                (unsigned int) response_code,
                (int) cpr.hr.ec);
    GNUNET_break_op (0);
    break;
  }
  cph->cb (cph->cb_cls,
           &cpr);
  TALER_MERCHANT_categories_post_cancel (cph);
}


struct TALER_MERCHANT_CategoriesPostHandle *
TALER_MERCHANT_categories_post (
  struct GNUNET_CURL_Context *ctx,
  const char *backend_url,
  const char *name,
  const json_t *name_i18n,
  TALER_MERCHANT_CategoriesPostCallback cb,
  void *cb_cls)
{
  struct TALER_MERCHANT_CategoriesPostHandle *cph;
  json_t *req_obj;

  req_obj = GNUNET_JSON_PACK (
    GNUNET_JSON_pack_string ("name",
                             name),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_object_incref ("name_i18n",
                                      (json_t *) name_i18n)));
  cph = GNUNET_new (struct TALER_MERCHANT_CategoriesPostHandle);
  cph->ctx = ctx;
  cph->cb = cb;
  cph->cb_cls = cb_cls;
  cph->url = TALER_url_join (backend_url,
                             "private/categories",
                             NULL);
  if (NULL == cph->url)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to build /private/categories URL\n");
    json_decref (req_obj);
    GNUNET_free (cph);
    return NULL;
  }
  {
    CURL *eh;

    eh = TALER_MERCHANT_curl_easy_get_ (cph->url);
    if (GNUNET_OK !=
        TALER_curl_easy_post (&cph->post_ctx,
                              eh,
                              req_obj))
    {
      GNUNET_break (0);
      curl_easy_cleanup (eh);
      json_decref (req_obj);
      GNUNET_free (cph->url);
      GNUNET_free (cph);
      return NULL;
    }
    json_decref (req_obj);
    cph->job = GNUNET_CURL_job_add2 (ctx,
                                     eh,
                                     cph->post_ctx.headers,
                                     &handle_post_categories_finished,
                                     cph);
  }
  return cph;
}


void
TALER_MERCHANT_categories_post_cancel (
  struct TALER_MERCHANT_CategoriesPostHandle *cph)
{
  if (NULL != cph->job)
  {
    GNUNET_CURL_job_cancel (cph->job);
    cph->job = NULL;
  }
  TALER_curl_easy_post_finished (&cph->post_ctx);
  GNUNET_free (cph->url);
  GNUNET_free (cph);
}


/* end of merchant_api_post_categories.c */
