/*
   This file is part of TALER
   Copyright (C) 2026 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 src/backenddb/update_token_family_key_expiration.c
 * @brief Implementation of the update_token_family_key_expiration function for Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_pq_lib.h>
#include <taler/taler_pq_lib.h>
#include "merchant-database/update_token_family_key_expiration.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_update_token_family_key_expiration (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *instance_id,
  const char *token_family_slug,
  struct GNUNET_TIME_Timestamp valid_at,
  struct GNUNET_TIME_Timestamp sign_until)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (token_family_slug),
    GNUNET_PQ_query_param_timestamp (&valid_at),
    GNUNET_PQ_query_param_timestamp (&sign_until),
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_assert (NULL != pg->current_merchant_id);
  GNUNET_assert (0 == strcmp (instance_id,
                              pg->current_merchant_id));
  TMH_PQ_prepare_anon (pg,
                       "UPDATE merchant_token_family_keys mtfk"
                       " SET private_key_deleted_at="
                       "   GREATEST (mtfk.private_key_deleted_at,$3)"
                       " FROM merchant_token_families mtf"
                       " WHERE (mtf.token_family_serial = mtfk.token_family_serial)"
                       "   AND (mtf.slug=$1)"
                       "   AND ($2 >= mtfk.signature_validity_start)"
                       "   AND ($2 <= mtfk.signature_validity_end)"
                       "   AND ($3 > mtfk.private_key_deleted_at)"
                       "   AND (mtfk.priv IS NOT NULL)");
  qs = GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                           "",
                                           params);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Extending MTFK %s valid at %llu to sign until %llu got %d\n",
              token_family_slug,
              (unsigned long long) valid_at.abs_time.abs_value_us,
              (unsigned long long) sign_until.abs_time.abs_value_us,
              (int) qs);
  return qs;
}
