/*
   This file is part of TALER
   Copyright (C) 2022 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 exchangedb/get_exists_aml_officer.c
 * @brief Implementation of the get_exists_aml_officer function for Postgres
 * @author Christian Grothoff
 */
#include "taler/taler_pq_lib.h"
#include "exchange-database/get_exists_aml_officer.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_get_exists_aml_officer (
  struct TALER_EXCHANGEDB_PostgresContext *pg,
  const struct TALER_AmlOfficerPublicKeyP *decider_pub,
  bool *read_only)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_auto_from_type (decider_pub),
    GNUNET_PQ_query_param_end
  };
  struct GNUNET_PQ_ResultSpec rs[] = {
    GNUNET_PQ_result_spec_bool ("read_only",
                                read_only),
    GNUNET_PQ_result_spec_end
  };

  /* aml_staff is append-only, so the officer's status is the row with the
     greatest last_change.  The is_active filter has to be applied to that
     row and only to it: filtering first would let any active status the
     officer ever held answer for one that has since been revoked. */
  PREPARE (pg,
           "get_exists_aml_officer",
           "SELECT read_only"
           "  FROM (SELECT is_active"
           "              ,read_only"
           "          FROM aml_staff"
           "         WHERE decider_pub=$1"
           "         ORDER BY last_change DESC"
           "         LIMIT 1) latest"
           " WHERE is_active;");
  return GNUNET_PQ_eval_prepared_singleton_select (pg->conn,
                                                   "get_exists_aml_officer",
                                                   params,
                                                   rs);
}
