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

   TALER is free software; you can redistribute it and/or modify it under the
   terms of the GNU 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 General Public License for more details.

   You should have received a copy of the GNU General Public License along with
   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file backenddb/pg_lookup_all_products.c
 * @brief Implementation of the lookup_all_products function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_lookup_all_products.h"
#include "pg_helper.h"

/**
 * Context used for TMH_PG_lookup_all_products().
 */
struct LookupProductsContext
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_ProductCallback cb;

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

  /**
   * Postgres context.
   */
  struct PostgresClosure *pg;

  /**
   * Did database result extraction fail?
   */
  bool extract_failed;
};


/**
 * Function to be called with the results of a SELECT statement
 * that has returned @a num_results results about products.
 *
 * @param[in,out] cls of type `struct LookupProductsContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
lookup_products_cb (void *cls,
                    PGresult *result,
                    unsigned int num_results)
{
  struct LookupProductsContext *plc = cls;
  struct PostgresClosure *pg = plc->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    char *product_id;
    uint64_t product_serial;
    struct TALER_MERCHANTDB_ProductDetails pd;
    size_t num_categories;
    uint64_t *categories;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_string ("product_id",
                                    &product_id),
      GNUNET_PQ_result_spec_uint64 ("product_serial",
                                    &product_serial),
      GNUNET_PQ_result_spec_string ("product_name",
                                    &pd.product_name),
      GNUNET_PQ_result_spec_string ("description",
                                    &pd.description),
      TALER_PQ_result_spec_json ("description_i18n",
                                 &pd.description_i18n),
      GNUNET_PQ_result_spec_string ("unit",
                                    &pd.unit),
      TALER_PQ_result_spec_amount_with_currency ("price",
                                                 &pd.price),
      TALER_PQ_result_spec_array_amount_with_currency (pg->conn,
                                                       "price_array",
                                                       &pd.price_array_length,
                                                       &pd.price_array),
      TALER_PQ_result_spec_json ("taxes",
                                 &pd.taxes),
      GNUNET_PQ_result_spec_uint64 ("total_stock",
                                    &pd.total_stock),
      GNUNET_PQ_result_spec_uint32 ("total_stock_frac",
                                    &pd.total_stock_frac),
      GNUNET_PQ_result_spec_bool ("allow_fractional_quantity",
                                  &pd.allow_fractional_quantity),
      GNUNET_PQ_result_spec_uint32 ("fractional_precision_level",
                                    &pd.fractional_precision_level),
      GNUNET_PQ_result_spec_uint64 ("total_sold",
                                    &pd.total_sold),
      GNUNET_PQ_result_spec_uint32 ("total_sold_frac",
                                    &pd.total_sold_frac),
      GNUNET_PQ_result_spec_uint64 ("total_lost",
                                    &pd.total_lost),
      GNUNET_PQ_result_spec_uint32 ("total_lost_frac",
                                    &pd.total_lost_frac),
      GNUNET_PQ_result_spec_string ("image",
                                    &pd.image),
      TALER_PQ_result_spec_json ("address",
                                 &pd.address),
      GNUNET_PQ_result_spec_timestamp ("next_restock",
                                       &pd.next_restock),
      GNUNET_PQ_result_spec_uint32 ("minimum_age",
                                    &pd.minimum_age),
      GNUNET_PQ_result_spec_array_uint64 (pg->conn,
                                          "categories",
                                          &num_categories,
                                          &categories),
      GNUNET_PQ_result_spec_end
    };

    if (GNUNET_OK !=
        GNUNET_PQ_extract_result (result,
                                  rs,
                                  i))
    {
      GNUNET_break (0);
      plc->extract_failed = true;
      return;
    }
    plc->cb (plc->cb_cls,
             product_serial,
             product_id,
             &pd,
             num_categories,
             categories);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_all_products (void *cls,
                            const char *instance_id,
                            TALER_MERCHANTDB_ProductCallback cb,
                            void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct LookupProductsContext plc = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg,
    /* Can be overwritten by the lookup_products_cb */
    .extract_failed = false,
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_all_products",
           "SELECT"
           " description"
           ",description_i18n::TEXT"
           ",product_name"
           ",unit"
           ",price"
           ",price_array"
           ",taxes::TEXT"
           ",total_stock"
           ",total_stock_frac"
           ",allow_fractional_quantity"
           ",fractional_precision_level"
           ",total_sold"
           ",total_sold_frac"
           ",total_lost"
           ",total_lost_frac"
           ",image"
           ",minv.address::TEXT"
           ",next_restock"
           ",minimum_age"
           ",product_id"
           ",product_serial"
           ",t.category_array AS categories"
           " FROM merchant_inventory minv"
           " JOIN merchant_instances inst"
           "   USING (merchant_serial)"
           ",LATERAL ("
           "   SELECT ARRAY ("
           "     SELECT mpc.category_serial"
           "       FROM merchant_product_categories mpc"
           "      WHERE mpc.product_serial = minv.product_serial"
           "   ) AS category_array"
           " ) t"
           " WHERE inst.merchant_id=$1");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_all_products",
    params,
    &lookup_products_cb,
    &plc);
  /* If there was an error inside lookup_products_cb, return a hard error. */
  if (plc.extract_failed)
    return GNUNET_DB_STATUS_HARD_ERROR;
  return qs;
}
