/*
   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 backenddb/pg_check_money_pots.c
 * @brief Implementation of the check_money_pots function for Postgres
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "pg_check_money_pots.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
TMH_PG_check_money_pots (void *cls,
                         const char *instance_id,
                         unsigned int pots_len,
                         uint64_t pots[static pots_len],
                         uint64_t *pot_missing)
{
  struct PostgresClosure *pg = cls;
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (instance_id),
    GNUNET_PQ_query_param_array_uint64 (pots_len,
                                        pots,
                                        pg->conn),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_uint64 ("out_missing",
                                  pot_missing),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "check_money_pots",
           "SELECT n AS out_missing"
           "  FROM UNNEST($2::INT8[]) AS n"
           " WHERE NOT EXISTS ("
           "  SELECT 1"
           "    FROM merchant_money_pots mmp"
           "    JOIN merchant_instances mi"
           "      USING (merchant_serial)"
           "   WHERE mmp.money_pot_serial=n"
           "     AND mi.merchant_id=$1"
           " )"
           " LIMIT 1;");
  qs = GNUNET_PQ_eval_prepared_singleton_select (
    pg->conn,
    "check_money_pots",
    params,
    rs);
  GNUNET_PQ_cleanup_query_params_closures (params);
  return qs;
}
