/*
   This file is part of Challenger
   Copyright (C) 2023 Taler Systems SA

   Challenger 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.

   Challenger 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
   Challenger; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
/**
 * @file src/challengerdb/insert_client.c
 * @brief Implementation of the insert_client function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <taler/taler_error_codes.h>
#include <taler/taler_dbevents.h>
#include <taler/taler_pq_lib.h>
#include "insert_client.h"
#include "pg_helper.h"


enum GNUNET_DB_QueryStatus
CHALLENGERDB_insert_client (struct CHALLENGERDB_PostgresContext *ctx,
                            const char *client_redirect_uri,
                            const char *client_secret,
                            uint64_t *client_id,
                            bool *uri_taken)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (client_redirect_uri),
    GNUNET_PQ_query_param_string (client_secret),
    GNUNET_PQ_query_param_end
  };
  bool inserted;
  bool taken;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_allow_null (
      GNUNET_PQ_result_spec_uint64 ("client_serial_id",
                                    client_id),
      NULL),
    GNUNET_PQ_result_spec_bool ("inserted",
                                &inserted),
    GNUNET_PQ_result_spec_bool ("uri_taken",
                                &taken),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  *client_id = 0;
  *uri_taken = false;
  /* The ON CONFLICT arbiter must be spelled out: a bare 'ON CONFLICT DO
     NOTHING' swallows *any* unique violation, including one on the primary
     key, which happens when the identity sequence of 'clients' lags behind
     max(client_serial_id) (e.g. after a restore that did not restore the
     sequence).  As GNUnet maps every unique violation to NO_RESULTS, the
     caller could not tell that apart from "this URI is already registered"
     either, so report whether the URI was taken; if it was not, the INSERT
     failed for a different reason and the caller must say so. */
  PREPARE (ctx,
           "insert_client",
           "WITH ins AS ("
           "  INSERT INTO clients"
           "   (uri"
           "   ,client_secret"
           "  ) VALUES "
           "  ($1, $2)"
           "  ON CONFLICT (uri) DO NOTHING"
           "  RETURNING client_serial_id"
           ") SELECT"
           "   (SELECT client_serial_id FROM ins) AS client_serial_id"
           "  ,EXISTS (SELECT 1 FROM ins) AS inserted"
           "  ,EXISTS (SELECT 1 FROM clients WHERE uri=$1) AS uri_taken;");
  qs = GNUNET_PQ_eval_prepared_singleton_select (ctx->conn,
                                                 "insert_client",
                                                 params,
                                                 rs);
  if (0 > qs)
    return qs;
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    return qs;
  *uri_taken = taken;
  if (! inserted)
  {
    *client_id = 0;
    return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
  }
  return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT;
}
