/*
   This file is part of Challenger
   Copyright (C) 2024 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/update_client.c
 * @brief Implementation of the update_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 "update_client.h"
#include "pg_helper.h"

enum GNUNET_DB_QueryStatus
CHALLENGERDB_update_client (struct CHALLENGERDB_PostgresContext *ctx,
                            uint64_t client_id,
                            const char *client_redirect_uri,
                            const char *client_secret,
                            bool *uri_conflict)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_uint64 (&client_id),
    GNUNET_PQ_query_param_string (client_redirect_uri),
    NULL == client_secret
    ? GNUNET_PQ_query_param_null ()
    : GNUNET_PQ_query_param_string (client_secret),
    GNUNET_PQ_query_param_end
  };
  bool updated;
  bool conflict;
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("updated",
                                &updated),
    GNUNET_PQ_result_spec_bool ("uri_conflict",
                                &conflict),
    GNUNET_PQ_result_spec_end
  };
  enum GNUNET_DB_QueryStatus qs;

  *uri_conflict = false;
  /* "No rows updated" has two very different causes here: the client does
     not exist, or another client already uses @a client_redirect_uri (which
     violates clients_uri_key, and GNUnet maps a unique violation to
     NO_RESULTS -- indistinguishable from "not found" at the API).  So detect
     the collision ourselves and refuse the UPDATE in that case, and report
     which of the two happened. */
  PREPARE (ctx,
           "update_client",
           "WITH target AS ("
           "  SELECT client_serial_id"
           "    FROM clients"
           "   WHERE client_serial_id=$1"
           "), taken AS ("
           "  SELECT client_serial_id"
           "    FROM clients"
           "   WHERE uri=$2"
           "     AND client_serial_id<>$1"
           "), upd AS ("
           "  UPDATE clients"
           "     SET uri=$2"
           "        ,client_secret=COALESCE($3,client_secret)"
           "   WHERE client_serial_id=$1"
           "     AND NOT EXISTS (SELECT 1 FROM taken)"
           "  RETURNING client_serial_id"
           ") SELECT"
           "   EXISTS (SELECT 1 FROM upd) AS updated"
           "  ,(     EXISTS (SELECT 1 FROM target)"
           "     AND EXISTS (SELECT 1 FROM taken) ) AS uri_conflict;");
  qs = GNUNET_PQ_eval_prepared_singleton_select (ctx->conn,
                                                 "update_client",
                                                 params,
                                                 rs);
  if (0 > qs)
    return qs;
  if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
  {
    /* Our SELECT always yields exactly one row, so zero rows can only be a
       unique violation on clients.uri: another transaction inserted the URI
       after our snapshot was taken. */
    *uri_conflict = true;
    return qs;
  }
  *uri_conflict = conflict;
  return updated
         ? GNUNET_DB_STATUS_SUCCESS_ONE_RESULT
         : GNUNET_DB_STATUS_SUCCESS_NO_RESULTS;
}
