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


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_delete_order (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  const char *order_id,
  bool force)
{
  struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (order_id),
    GNUNET_PQ_query_param_absolute_time (&now),
    GNUNET_PQ_query_param_bool (force),
    GNUNET_PQ_query_param_end
  };
  bool deleted;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("deleted",
                                &deleted),
    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));
  /* Note: this MUST be a single stored procedure: deleting the order and
     the associated contract terms in two separate statements would run in
     two separate transactions (the caller does not open one), and a failure
     between them would orphan the contract terms. */
  TMH_PQ_prepare_anon (pg,
                       "SELECT"
                       " out_deleted AS deleted"
                       " FROM merchant_do_delete_order"
                       "($1,$2,$3);");
  qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                 "",
                                                 params,
                                                 rs);
  if (qs <= 0)
    return qs;
  return deleted
         ? GNUNET_DB_STATUS_SUCCESS_ONE_RESULT
         : GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
}
