#ifndef NSIGNER_AUTH_ENVELOPE_H
#define NSIGNER_AUTH_ENVELOPE_H

#include <stddef.h>
#include <stdint.h>
#include <time.h>

#include <cJSON.h>

#define AUTH_NONCE_CACHE_SIZE 1024
#define AUTH_DEFAULT_SKEW_SECONDS 30
#define AUTH_EVENT_KIND 27235

#define AUTH_ERR_ENVELOPE_MALFORMED 2010
#define AUTH_ERR_BODY_MISMATCH 2011
#define AUTH_ERR_SIGNATURE_INVALID 2012
#define AUTH_ERR_KIND_INVALID 2013
#define AUTH_ERR_ENVELOPE_REQUIRED 2014
#define AUTH_ERR_ENVELOPE_MISMATCH 2015
#define AUTH_ERR_ENVELOPE_STALE 2016
#define AUTH_ERR_REPLAY_DETECTED 2017

typedef struct {
    uint8_t ids[AUTH_NONCE_CACHE_SIZE][32];
    int count;
    int next;
} auth_nonce_cache_t;

void auth_nonce_cache_init(auth_nonce_cache_t *cache);

int auth_envelope_verify_request(const char *request_json,
                                 auth_nonce_cache_t *cache,
                                 int skew_seconds,
                                 char *out_pubkey_hex,
                                 size_t out_pubkey_hex_sz,
                                 char *out_label,
                                 size_t out_label_sz,
                                 int *out_error_code,
                                 const char **out_error_message);

int auth_envelope_build_for_request(const char *request_id,
                                    const char *method,
                                    const cJSON *params,
                                    const unsigned char privkey[32],
                                    const char *label,
                                    time_t created_at,
                                    cJSON **out_auth);

#endif