/*
  This file is part of TALER
  (C) 2024 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser 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 taler-merchant-httpd_contract.c
 * @brief shared logic for contract terms handling
 * @author Christian Blättler
 */
#include "platform.h"
#include <gnunet/gnunet_common.h>
#include <jansson.h>
#include <stdint.h>
#include <taler/taler_json_lib.h>
#include "taler-merchant-httpd_contract.h"


enum GNUNET_GenericReturnValue
TMH_find_token_family_key (
  const char *slug,
  struct GNUNET_TIME_Timestamp valid_after,
  const struct TALER_MERCHANT_ContractTokenFamily *families,
  unsigned int families_len,
  struct TALER_MERCHANT_ContractTokenFamily *family,
  struct TALER_MERCHANT_ContractTokenFamilyKey *key)
{
  for (unsigned int i = 0; i < families_len; i++)
  {
    const struct TALER_MERCHANT_ContractTokenFamily *fami
      = &families[i];

    if (0 != strcmp (fami->slug,
                     slug))
      continue;
    if (NULL != family)
      *family = *fami;
    for (unsigned int k = 0; k < fami->keys_len; k++)
    {
      struct TALER_MERCHANT_ContractTokenFamilyKey *ki = &fami->keys[k];

      if (GNUNET_TIME_timestamp_cmp (ki->valid_after,
                                     ==,
                                     valid_after))
      {
        if (NULL != key)
          *key = *ki;
        return GNUNET_OK;
      }
    }
    /* matching family found, but no key. */
    return GNUNET_NO;
  }

  /* no matching family found */
  return GNUNET_SYSERR;
}
