/*
  This file is part of Anastasis
  Copyright (C) 2020-2022 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Anastasis 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file stasis/do_insert_recovery_document.c
 * @brief Anastasis database: do insert recovery document
 * @author Christian Grothoff
 */
#include "platform.h"
#include "anastasis-db_pg.h"
#include "anastasis/anastasis-database/do_insert_recovery_document.h"
#include "anastasis/anastasis-database/transaction.h"
#include "anastasis/anastasis-database/preflight.h"
#include <taler/taler_pq_lib.h>


/**
 * Store encrypted recovery document.
 *
 * @param account_pub public key of the user's account
 * @param account_sig signature affirming storage request
 * @param recovery_data_hash hash of @a data
 * @param recovery_data contains encrypted_recovery_document
 * @param recovery_data_size size of data blob
 * @param payment_secret identifier for the payment, used to later charge on uploads
 * @param[out] version set to the version assigned to the document by the database
 * @return transaction status, 0 if upload could not be finished because @a payment_secret
 *         did not have enough upload left; HARD error if @a payment_secret is unknown, ...
 */
enum ANASTASIS_DB_StoreStatus
ANASTASIS_DB_do_insert_recovery_document (
  const struct ANASTASIS_CRYPTO_AccountPublicKeyP *account_pub,
  const struct ANASTASIS_AccountSignatureP *account_sig,
  const struct GNUNET_HashCode *recovery_data_hash,
  const void *recovery_data,
  size_t recovery_data_size,
  const void *recovery_meta_data,
  size_t recovery_meta_data_size,
  const struct ANASTASIS_PaymentSecretP *payment_secret,
  uint32_t *version)
{
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_break (GNUNET_OK ==
                ANASTASIS_DB_preflight ());

  PREPARE ("do_insert_recovery_document_select_account",
           "SELECT"
           " expiration_date "
           "FROM anastasis_user"
           " WHERE user_id=$1"
           " FOR UPDATE;");
  PREPARE ("do_insert_recovery_document_select_latest_version",
           "SELECT"
           " version"
           ",recovery_data_hash"
           ",expiration_date"
           " FROM anastasis_recoverydocument"
           " JOIN anastasis_user USING (user_id)"
           " WHERE user_id=$1"
           " ORDER BY version DESC"
           " LIMIT 1;");
  PREPARE ("do_insert_recovery_document_select_post_counter",
           "SELECT"
           " post_counter"
           " FROM anastasis_recdoc_payment"
           " WHERE user_id=$1"
           "  AND payment_identifier=$2;");
  PREPARE ("do_insert_recovery_document_update_post_counter",
           "UPDATE"
           " anastasis_recdoc_payment"
           " SET"
           " post_counter=$1"
           " WHERE user_id =$2"
           "   AND payment_identifier=$3;");
  PREPARE ("do_insert_recovery_document_insert",
           "INSERT INTO anastasis_recoverydocument "
           "(user_id"
           ",version"
           ",account_sig"
           ",recovery_data_hash"
           ",recovery_data"
           ",recovery_meta_data"
           ",creation_date"
           ") VALUES "
           "($1, $2, $3, $4, $5, $6, $7);");
  for (unsigned int retry = 0; retry<MAX_RETRIES; retry++)
  {
    if (GNUNET_OK !=
        ANASTASIS_DB_start (
          "do_insert_recovery_document"))
    {
      GNUNET_break (0);
      return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
    }
    /* get the current version and hash of the latest recovery document
       for this account */
    {
      struct GNUNET_HashCode dh;
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_uint32 ("version",
                                      version),
        GNUNET_PQ_result_spec_auto_from_type ("recovery_data_hash",
                                              &dh),
        GNUNET_PQ_result_spec_end
      };

      qs = GNUNET_PQ_eval_prepared_singleton_select (
        pg->conn,
        "do_insert_recovery_document_select_latest_version",
        params,
        rs);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        GNUNET_break (0);
        ANASTASIS_DB_rollback ();
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        *version = 1;
        break;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        /* had an existing recovery_data, is it identical? */
        if (0 == GNUNET_memcmp (&dh,
                                recovery_data_hash))
        {
          /* Yes. Previous identical recovery data exists */
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_NO_RESULTS;
        }
        (*version)++;
        break;
      default:
        GNUNET_break (0);
        ANASTASIS_DB_rollback ();
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      }
    }

    /* First, check if account exists */
    {
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_end
      };
      struct GNUNET_PQ_ResultSpec rs[] = {
        GNUNET_PQ_result_spec_end
      };

      qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                     "do_insert_recovery_document_select_account",
                                                     params,
                                                     rs);
    }
    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
      ANASTASIS_DB_rollback ();
      return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
    case GNUNET_DB_STATUS_SOFT_ERROR:
      goto retry;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      ANASTASIS_DB_rollback ();
      return ANASTASIS_DB_STORE_STATUS_PAYMENT_REQUIRED;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      /* handle interesting case below */
      break;
    }

    {
      uint32_t postcounter;

      /* lookup if the user has enough uploads left and decrement */
      {
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_auto_from_type (account_pub),
          GNUNET_PQ_query_param_auto_from_type (payment_secret),
          GNUNET_PQ_query_param_end
        };
        struct GNUNET_PQ_ResultSpec rs[] = {
          GNUNET_PQ_result_spec_uint32 ("post_counter",
                                        &postcounter),
          GNUNET_PQ_result_spec_end
        };

        qs = GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                       "do_insert_recovery_document_select_post_counter",
                                                       params,
                                                       rs);
        switch (qs)
        {
        case GNUNET_DB_STATUS_HARD_ERROR:
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SOFT_ERROR:
          goto retry;
        case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
          break;
        }
      }

      if (0 == postcounter)
      {
        ANASTASIS_DB_rollback ();
        return ANASTASIS_DB_STORE_STATUS_STORE_LIMIT_EXCEEDED;
      }
      /* Decrement the postcounter by one */
      postcounter--;

      /* Update the postcounter in the Database */
      {
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_uint32 (&postcounter),
          GNUNET_PQ_query_param_auto_from_type (account_pub),
          GNUNET_PQ_query_param_auto_from_type (payment_secret),
          GNUNET_PQ_query_param_end
        };

        qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                                 "do_insert_recovery_document_update_post_counter",
                                                 params);
        switch (qs)
        {
        case GNUNET_DB_STATUS_HARD_ERROR:
          GNUNET_break (0);
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SOFT_ERROR:
          goto retry;
        case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
          GNUNET_break (0);
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
          break;
        default:
          GNUNET_break (0);
          ANASTASIS_DB_rollback ();
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        }
      }
    }

    /* finally, actually insert the recovery document */
    {
      struct GNUNET_TIME_Timestamp now
        = GNUNET_TIME_timestamp_get ();
      struct GNUNET_PQ_QueryParam params[] = {
        GNUNET_PQ_query_param_auto_from_type (account_pub),
        GNUNET_PQ_query_param_uint32 (version),
        GNUNET_PQ_query_param_auto_from_type (account_sig),
        GNUNET_PQ_query_param_auto_from_type (recovery_data_hash),
        GNUNET_PQ_query_param_fixed_size (recovery_data,
                                          recovery_data_size),
        GNUNET_PQ_query_param_fixed_size (recovery_meta_data,
                                          recovery_meta_data_size),
        GNUNET_PQ_query_param_timestamp (&now),
        GNUNET_PQ_query_param_end
      };

      qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                               "do_insert_recovery_document_insert",
                                               params);
      switch (qs)
      {
      case GNUNET_DB_STATUS_HARD_ERROR:
        ANASTASIS_DB_rollback ();
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SOFT_ERROR:
        goto retry;
      case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
        GNUNET_break (0);
        ANASTASIS_DB_rollback ();
        return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
      case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
        qs = ANASTASIS_DB_commit ();
        if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
          goto retry;
        if (qs < 0)
          return ANASTASIS_DB_STORE_STATUS_HARD_ERROR;
        return ANASTASIS_DB_STORE_STATUS_SUCCESS;
      }
    }
retry:
    ANASTASIS_DB_rollback ();
  }
  return ANASTASIS_DB_STORE_STATUS_SOFT_ERROR;
}


/* end of do_insert_recovery_document.c */
