/*
  This file is part of TALER
  Copyright (C) 2024 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 testing/testing_api_cmd_donation_statement_get.c
 * @brief Implement the GET /donation-statement/$YEAR/$HASH_DONOR_ID test command.
 * @author Marcello Stanisci
 * @author Lukas Matyja
 */
#include <donau_config.h>
#include <taler/taler_json_lib.h>
#include <gnunet/gnunet_curl_lib.h>
#include <taler/taler_testing_lib.h>
#include "donau_testing_lib.h"


/**
 * State for a "status" CMD.
 */
struct StatusState
{
  /**
   * Handle to the "charity status" operation.
   */
  struct DONAU_DonationStatementGetHandle *dsgh;

  /**
   * Expected HTTP response code.
   */
  unsigned int expected_response_code;

  /**
   * Interpreter state.
   */
  struct TALER_TESTING_Interpreter *is;

  /**
   * The Donation Statement
   */
  struct DONAU_DonationStatement donation_statement;

  /**
   * The Donau keys
   */
  struct DONAU_Keys *keys;

};

/**
 * Check that the reserve balance and HTTP response code are
 * both acceptable.
 *
 * @param cls closure.
 * @param dsr HTTP response details
 */
static void
donation_statement_status_cb (void *cls,
                              const struct DONAU_DonationStatementResponse *dsr)
{
  struct StatusState *ss = cls;

  ss->dsgh = NULL;
  if (ss->expected_response_code != dsr->hr.http_status)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected HTTP response code: %d in %s:%u\n",
                dsr->hr.http_status,
                __FILE__,
                __LINE__);
    json_dumpf (dsr->hr.reply,
                stderr,
                0);
    TALER_TESTING_interpreter_fail (ss->is);
    return;
  }

  /* Get donau keys from trait */
  {
    const struct TALER_TESTING_Command *keys_cmd;
    struct DONAU_Keys *keys;

    keys_cmd = TALER_TESTING_interpreter_lookup_command (ss->is,
                                                         "get-donau");

    if (GNUNET_OK !=
        TALER_TESTING_get_trait_donau_keys (keys_cmd,
                                            &keys))
    {
      GNUNET_break (0);
      TALER_TESTING_interpreter_fail (ss->is);
      return;
    }
    ss->keys = keys;
  }

  ss->donation_statement.total_amount = dsr->details.ok.total_amount;
  ss->donation_statement.donation_statement_sig =
    dsr->details.ok.donation_statement_sig;

  for (unsigned int i = 0; i < ss->keys->num_sign_keys; i++)
  {
    if (GNUNET_OK == DONAU_donation_statement_verify (
          &ss->donation_statement.total_amount,
          ss->donation_statement.year,
          ss->donation_statement.
          h_donor_tax_id,
          &dsr->details.ok.donau_pub,
          &ss->donation_statement.
          donation_statement_sig))
    {
      char *qr_string = DONAU_generate_qr_string (&dsr->details.ok.donau_pub,
                                                  &ss->donation_statement);
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "qr-string: %s\n", qr_string);
      GNUNET_free (qr_string);

      TALER_TESTING_interpreter_next (ss->is);
      return;
    }
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Verify donation statement signature failed!");
  TALER_TESTING_interpreter_fail (ss->is);
  return;
}


/**
 * Run the command.
 *
 * @param cls closure.
 * @param cmd the command being executed.
 * @param is the interpreter state.
 */
static void
status_run (void *cls,
            const struct TALER_TESTING_Command *cmd,
            struct TALER_TESTING_Interpreter *is)
{
  struct StatusState *ss = cls;

  (void) cmd;
  ss->is = is;
  /* Get charity salted tax id hash from trait */
  {
    const struct TALER_TESTING_Command *issue_receipts_cmd;
    const struct DONAU_HashDonorTaxId *h_donor_tax_id;
    const char *donor_salt;
    const char *donor_tax_id;

    issue_receipts_cmd = TALER_TESTING_interpreter_lookup_command (is,
                                                                   "issue-receipts");

    if (GNUNET_OK != TALER_TESTING_get_trait_salted_tax_id_hash
          (issue_receipts_cmd, &h_donor_tax_id) ||
        GNUNET_OK != TALER_TESTING_get_trait_donor_salt
          (issue_receipts_cmd, &donor_salt) ||
        GNUNET_OK != TALER_TESTING_get_trait_donor_tax_id
          (issue_receipts_cmd, &donor_tax_id))
    {
      GNUNET_break (0);
      TALER_TESTING_interpreter_fail (is);
      return;
    }
    ss->donation_statement.donor_tax_id = donor_tax_id;
    ss->donation_statement.salt = donor_salt;
    ss->donation_statement.h_donor_tax_id = h_donor_tax_id;
  }

  ss->dsgh = DONAU_donation_statement_get (
    TALER_TESTING_interpreter_get_context (is),
    TALER_TESTING_get_donau_url (is),
    ss->donation_statement.year,
    ss->donation_statement.h_donor_tax_id,
    &donation_statement_status_cb,
    ss);
}


/**
 * Cleanup the state from a "reserve status" CMD, and possibly
 * cancel a pending operation thereof.
 *
 * @param cls closure.
 * @param cmd the command which is being cleaned up.
 */
static void
status_cleanup (void *cls,
                const struct TALER_TESTING_Command *cmd)
{
  struct StatusState *ss = cls;

  if (NULL != ss->dsgh)
  {
    // log incomplete command
    TALER_TESTING_command_incomplete (ss->is,
                                      cmd->label);
    DONAU_donation_statement_get_cancel (ss->dsgh);
    ss->dsgh = NULL;
  }
  GNUNET_free (ss);
}


struct TALER_TESTING_Command
TALER_TESTING_cmd_donation_statement_get (const char *label,
                                          uint64_t year,
                                          unsigned int expected_response_code)
{
  struct StatusState *ss;
  ss = GNUNET_new (struct StatusState);
  ss->donation_statement.year = year;
  ss->expected_response_code = expected_response_code;
  {
    struct TALER_TESTING_Command cmd = {
      .cls = ss,
      .label = label,
      .run = &status_run,
      .cleanup = &status_cleanup
    };

    return cmd;
  }
}
