/*
   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 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 src/backenddb/iterate_inventory_products_filtered.c
 * @brief Lookup inventory product details for templates (filtered)
 * @author Bohdan Potuzhnyi
 */
#include "platform.h"
#include <taler/taler_pq_lib.h>
#include "merchant-database/iterate_inventory_products_filtered.h"
#include "helper.h"


/**
 * Context used for TALER_MERCHANTDB_iterate_inventory_products_filtered().
 */
struct LookupInventoryProductsContext
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_InventoryProductCallback cb;

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

  /**
   * Postgres context for callbacks.
   */
  struct TALER_MERCHANTDB_PostgresContext *pg;

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


static void
lookup_inventory_products_cb (void *cls,
                              PGresult *result,
                              unsigned int num_results)
{
  struct LookupInventoryProductsContext *plc = cls;
  struct TALER_MERCHANTDB_PostgresContext *pg = plc->pg;

  for (unsigned int i = 0; i < num_results; i++)
  {
    char *product_id;
    struct TALER_MERCHANTDB_InventoryProductDetails pd;
    size_t num_categories;
    uint64_t *categories;
    bool no_image_hash;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_string ("product_id",
                                    &product_id),
      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_array_amount_with_currency (pg->conn,
                                                       "merchant",
                                                       "price_array",
                                                       &pd.price_array_length,
                                                       &pd.price_array),
      GNUNET_PQ_result_spec_uint64 ("remaining_stock",
                                    &pd.remaining_stock),
      GNUNET_PQ_result_spec_uint32 ("remaining_stock_frac",
                                    &pd.remaining_stock_frac),
      TALER_PQ_result_spec_json ("taxes",
                                 &pd.taxes),
      GNUNET_PQ_result_spec_allow_null (
        GNUNET_PQ_result_spec_string ("image_hash",
                                      &pd.image_hash),
        &no_image_hash),
      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_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_id,
             &pd,
             num_categories,
             categories);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_iterate_inventory_products_filtered (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  const char *const *product_ids,
  size_t num_product_ids,
  const uint64_t *categories,
  size_t num_categories,
  TALER_MERCHANTDB_InventoryProductCallback cb,
  void *cb_cls)
{
  struct LookupInventoryProductsContext plc = {
    .cb = cb,
    .cb_cls = cb_cls,
    .pg = pg,
    /* Can be overwritten by the lookup_inventory_products_cb */
    .extract_failed = false,
  };
  struct GNUNET_PQ_QueryParam params[] = {
    (0 == num_product_ids)
    ? GNUNET_PQ_query_param_null ()
    : GNUNET_PQ_query_param_array_ptrs_string (
      num_product_ids,
      (const char **) product_ids,
      pg->conn),
    (0 == num_categories)
    ? GNUNET_PQ_query_param_null ()
    : GNUNET_PQ_query_param_array_uint64 (num_categories,
                                          categories,
                                          pg->conn),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  GNUNET_assert (0 == strcmp (instance_id,
                              pg->current_merchant_id));
  TMH_PQ_prepare_anon (pg,
                       "SELECT"
                       " description"
                       ",description_i18n::TEXT"
                       ",product_name"
                       ",unit"
                       ",price_array"
                       ",CASE WHEN minv.total_stock = 9223372036854775807"
                       "      THEN minv.total_stock"
                       "      ELSE (GREATEST(0, rt.remaining_total) / 1000000)::INT8"
                       "      END AS remaining_stock"
                       ",CASE WHEN minv.total_stock = 9223372036854775807"
                       "      THEN 2147483647"
                       "      ELSE mod(GREATEST(0, rt.remaining_total), 1000000)::INT4"
                       "      END AS remaining_stock_frac"
                       ",taxes::TEXT"
                       ",image_hash"
                       ",allow_fractional_quantity"
                       ",fractional_precision_level"
                       ",product_id"
                       ",t.category_array AS categories"
                       " FROM merchant_inventory minv"
                       ",LATERAL ("
                       "   SELECT ARRAY ("
                       "     SELECT mpc.category_serial"
                       "       FROM merchant_product_categories mpc"
                       "      WHERE mpc.product_serial = minv.product_serial"
                       "   ) AS category_array"
                       " ) t"
                       ",LATERAL ("
                       "   SELECT COALESCE(SUM(total_locked::NUMERIC * 1000000"
                       "                        + total_locked_frac::NUMERIC), 0)"
                       "          AS total_locked"
                       "     FROM merchant_inventory_locks mil"
                       "    WHERE mil.product_serial = minv.product_serial"
                       " ) il"
                       ",LATERAL ("
                       "   SELECT COALESCE(SUM(total_locked::NUMERIC * 1000000"
                       "                        + total_locked_frac::NUMERIC), 0)"
                       "          AS total_locked"
                       "     FROM merchant_order_locks mol"
                       "    WHERE mol.product_serial = minv.product_serial"
                       " ) ol"
                       ",LATERAL ("
                       "   SELECT"
                       "     (minv.total_stock::NUMERIC * 1000000"
                       "      + minv.total_stock_frac::NUMERIC)"
                       "     - (minv.total_sold::NUMERIC * 1000000"
                       "        + minv.total_sold_frac::NUMERIC)"
                       "     - (minv.total_lost::NUMERIC * 1000000"
                       "        + minv.total_lost_frac::NUMERIC)"
                       "     - il.total_locked"
                       "     - ol.total_locked"
                       "     AS remaining_total"
                       " ) rt"
                       " WHERE ("
                       "     (COALESCE (array_length ($1::TEXT[], 1), 0) > 0"
                       "      AND minv.product_id = ANY ($1::TEXT[]))"
                       "     OR"
                       "     (COALESCE (array_length ($2::BIGINT[], 1), 0) > 0"
                       "      AND EXISTS ("
                       "        SELECT 1"
                       "          FROM merchant_product_categories mpc"
                       "         WHERE mpc.product_serial = minv.product_serial"
                       "           AND mpc.category_serial = ANY ($2::BIGINT[])"
                       "      ))"
                       "   )");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "",
    params,
    &lookup_inventory_products_cb,
    &plc);
  GNUNET_PQ_cleanup_query_params_closures (params);
  /* If there was an error inside lookup_inventory_products_cb, return a hard error. */
  if (plc.extract_failed)
    return GNUNET_DB_STATUS_HARD_ERROR;
  return qs;
}
