/*
   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_lookup_reports_pending.c
 * @brief Implementation of the lookup_reports_pending 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_lookup_reports_pending.h"
#include "pg_helper.h"


/**
 * Context used for TMH_PG_lookup_reports_pending().
 */
struct SelectReportsContext
{
  /**
   * Function to call with the results.
   */
  TALER_MERCHANTDB_ReportsPendingCallback cb;

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

  /**
   * 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 reports.
 *
 * @param[in,out] cls of type `struct SelectReportsContext *`
 * @param result the postgres result
 * @param num_results the number of results in @a result
 */
static void
select_pending_reports_cb (void *cls,
                           PGresult *result,
                           unsigned int num_results)
{
  struct SelectReportsContext *plc = cls;

  for (unsigned int i = 0; i < num_results; i++)
  {
    char *instance_id;
    uint64_t report_serial;
    char *report_program_section;
    char *report_description;
    char *mime_type;
    struct TALER_MERCHANT_ReportToken report_token;
    char *target_address;
    struct GNUNET_TIME_Relative frequency;
    struct GNUNET_TIME_Relative frequency_shift;
    struct GNUNET_TIME_Absolute next_transmission;
    bool one_shot;
    struct GNUNET_PQ_ResultSpec rs[] = {
      GNUNET_PQ_result_spec_string ("merchant_id",
                                    &instance_id),
      GNUNET_PQ_result_spec_uint64 ("report_serial",
                                    &report_serial),
      GNUNET_PQ_result_spec_string ("report_program_section",
                                    &report_program_section),
      GNUNET_PQ_result_spec_string ("report_description",
                                    &report_description),
      GNUNET_PQ_result_spec_string ("mime_type",
                                    &mime_type),
      GNUNET_PQ_result_spec_auto_from_type ("report_token",
                                            &report_token),
      GNUNET_PQ_result_spec_string ("target_address",
                                    &target_address),
      GNUNET_PQ_result_spec_relative_time ("frequency",
                                           &frequency),
      GNUNET_PQ_result_spec_relative_time ("frequency_shift",
                                           &frequency_shift),
      GNUNET_PQ_result_spec_absolute_time ("next_transmission",
                                           &next_transmission),
      GNUNET_PQ_result_spec_bool ("one_shot_hidden",
                                  &one_shot),
      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,
             instance_id,
             report_serial,
             report_program_section,
             report_description,
             mime_type,
             &report_token,
             target_address,
             frequency,
             frequency_shift,
             next_transmission,
             one_shot);
    GNUNET_PQ_cleanup_result (rs);
  }
}


enum GNUNET_DB_QueryStatus
TMH_PG_lookup_reports_pending (void *cls,
                               TALER_MERCHANTDB_ReportsPendingCallback cb,
                               void *cb_cls)
{
  struct PostgresClosure *pg = cls;
  struct SelectReportsContext plc = {
    .cb = cb,
    .cb_cls = cb_cls,
    /* Can be overwritten by the lookup_reports_cb */
    .extract_failed = false,
  };
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  check_connection (pg);
  PREPARE (pg,
           "lookup_reports_pending",
           "SELECT"
           "  mi.merchant_id"
           " ,mr.report_serial"
           " ,mr.report_program_section"
           " ,mr.report_description"
           " ,mr.mime_type"
           " ,mr.report_token"
           " ,mr.target_address"
           " ,mr.frequency"
           " ,mr.frequency_shift"
           " ,mr.next_transmission"
           " ,mr.one_shot_hidden"
           " FROM merchant_reports mr"
           " JOIN merchant_instances mi"
           "   USING (merchant_serial)"
           " ORDER BY next_transmission ASC"
           " LIMIT 1;");
  qs = GNUNET_PQ_eval_prepared_multi_select (
    pg->conn,
    "lookup_reports_pending",
    params,
    &select_pending_reports_cb,
    &plc);
  /* If there was an error inside select_pending_reports_cb, return a hard error. */
  if (plc.extract_failed)
  {
    GNUNET_break (0);
    return GNUNET_DB_STATUS_HARD_ERROR;
  }
  return qs;
}
