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

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, 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 Affero General Public License for more
  details.

  You should have received a copy of the GNU Affero General Public License
  along with TALER; see the file COPYING.  If not, see
  <http://www.gnu.org/licenses/>
*/
/**
 * @file taler-merchant-httpd_post-private-groups.c
 * @brief implementation of POST /private/groups
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include "taler-merchant-httpd_post-private-groups.h"
#include <taler/taler_json_lib.h>


MHD_RESULT
TMH_private_post_groups (const struct TMH_RequestHandler *rh,
                         struct MHD_Connection *connection,
                         struct TMH_HandlerContext *hc)
{
  const char *group_name;
  const char *description;
  enum GNUNET_DB_QueryStatus qs;
  uint64_t group_id;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_string ("group_name",
                             &group_name),
    GNUNET_JSON_spec_string ("description",
                             &description),
    GNUNET_JSON_spec_end ()
  };

  (void) rh;
  {
    enum GNUNET_GenericReturnValue res;

    res = TALER_MHD_parse_json_data (connection,
                                     hc->request_body,
                                     spec);
    if (GNUNET_OK != res)
    {
      GNUNET_break_op (0);
      return (GNUNET_NO == res)
             ? MHD_YES
             : MHD_NO;
    }
  }

  qs = TMH_db->insert_product_group (TMH_db->cls,
                                     hc->instance->settings.id,
                                     group_name,
                                     description,
                                     &group_id);
  if (qs < 0)
  {
    GNUNET_break (0);
    return TALER_MHD_reply_with_error (connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       TALER_EC_GENERIC_DB_STORE_FAILED,
                                       "insert_product_group");
  }
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
  {
    /* Zero will be returned on conflict */
    return TALER_MHD_reply_with_error (connection,
                                       MHD_HTTP_CONFLICT,
                                       TALER_EC_MERCHANT_PRIVATE_PRODUCT_GROUP_CONFLICTING_NAME,
                                       group_name);
  }

  return TALER_MHD_REPLY_JSON_PACK (
    connection,
    MHD_HTTP_OK,
    GNUNET_JSON_pack_uint64 ("group_serial_id",
                             group_id));
}
