create extension if not exists pgcrypto; create table if not exists api_keys ( id uuid primary key default gen_random_uuid(), app text not null, name text not null, prefix text not null, key_hash text not null unique, from_domain text not null default 'hubsport.club', allowed_from text[], daily_limit integer not null default 500, monthly_limit integer not null default 15000, revoked_at timestamptz, last_used_at timestamptz, created_at timestamptz not null default now() ); create table if not exists messages ( id uuid primary key default gen_random_uuid(), api_key_id uuid references api_keys(id) on delete set null, app text not null, provider_message_id text, from_email text not null, from_name text, to_emails text[] not null default '{}', cc_emails text[] not null default '{}', bcc_emails text[] not null default '{}', reply_to text[] not null default '{}', subject text not null, status text not null default 'queued', error text, payload jsonb not null, idempotency_key text, attempts integer not null default 0, next_attempt_at timestamptz not null default now(), created_at timestamptz not null default now(), sent_at timestamptz, completed_at timestamptz ); create index if not exists messages_queue_idx on messages (next_attempt_at) where status = 'queued'; create index if not exists messages_created_idx on messages (created_at desc); create index if not exists messages_key_created_idx on messages (api_key_id, created_at desc); create index if not exists messages_provider_idx on messages (provider_message_id); create unique index if not exists messages_idempotency_idx on messages (api_key_id, idempotency_key); create table if not exists message_events ( id bigserial primary key, message_id uuid references messages(id) on delete cascade, sns_message_id text unique, type text not null, payload jsonb not null, created_at timestamptz not null default now() ); create index if not exists message_events_message_idx on message_events (message_id, created_at); create table if not exists suppressions ( email text primary key, reason text not null, created_at timestamptz not null default now() );