/*
   This file is part of TALER
   Copyright (C) 2022 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/insert_inventory_lock.c
 * @brief Implementation of the insert_inventory_lock function for Postgres
 * @author Iván Ávalos
 */
#include "platform.h"
#include <taler/taler_pq_lib.h>
#include "merchant-database/insert_inventory_lock.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_insert_inventory_lock (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  const char *product_id,
  const struct GNUNET_Uuid *uuid,
  uint64_t quantity,
  uint32_t quantity_frac,
  struct GNUNET_TIME_Timestamp expiration_time)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (product_id),
    GNUNET_PQ_query_param_auto_from_type (uuid),
    GNUNET_PQ_query_param_uint64 (&quantity),
    GNUNET_PQ_query_param_uint32 (&quantity_frac),
    GNUNET_PQ_query_param_timestamp (&expiration_time),
    GNUNET_PQ_query_param_end
  };
  bool no_product = false;
  bool insufficient_stock = false;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("out_no_product",
                                &no_product),
    GNUNET_PQ_result_spec_bool ("out_insufficient_stock",
                                &insufficient_stock),
    GNUNET_PQ_result_spec_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"
                       "  out_no_product"
                       " ,out_insufficient_stock"
                       "  FROM merchant_do_insert_inventory_lock"
                       " ($1, $2, $3, $4, $5);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "",
                                                 params,
                                                 rs);
  if (qs <= 0)
    return qs;
  if (no_product || insufficient_stock)
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  return qs;
}
