-- Wever Labs Provider Activation Binding v1
-- Provider confirmations become credit funding events, settlement receipts, and run eligibility records.

create table if not exists provider_webhook_verifications (
  id uuid primary key default gen_random_uuid(),
  verification_id text unique not null,
  provider_id text not null,
  event_id text not null,
  event_type text,
  signature_status text not null,
  idempotency_key text,
  verification_state text not null,
  provider_reference text,
  raw_event_hash text,
  normalized_payload jsonb default '{}'::jsonb,
  received_at timestamptz default now(),
  verified_at timestamptz default now(),
  created_at timestamptz default now()
);

create table if not exists provider_activation_bindings (
  id uuid primary key default gen_random_uuid(),
  activation_id text unique not null,
  provider_id text not null,
  route_id text not null,
  settlement_id text not null,
  confirmation_id text not null,
  credit_entitlement_id text not null,
  agent_id text,
  task_token text,
  run_contract_id text,
  runtime_record_id text,
  activation_state text not null,
  credits_funded numeric default 0,
  credit_account_id text,
  settlement_receipt_url text,
  result_contract_url text,
  callback_url text,
  provider_reference text,
  verification_id text,
  next_action text,
  payload jsonb default '{}'::jsonb,
  created_at timestamptz default now(),
  activated_at timestamptz default now()
);

create table if not exists credit_funding_events (
  id uuid primary key default gen_random_uuid(),
  funding_event_id text unique not null,
  credit_entitlement_id text not null,
  credit_account_id text not null,
  agent_id text,
  task_token text,
  source_provider text not null,
  settlement_id text,
  confirmation_id text,
  credits_funded numeric not null,
  credit_currency text default 'wever_os_credit',
  settlement_receipt_id text,
  settlement_receipt_url text,
  funding_state text not null default 'funded',
  created_at timestamptz default now()
);

create index if not exists idx_provider_activation_task_token on provider_activation_bindings(task_token);
create index if not exists idx_provider_activation_settlement_id on provider_activation_bindings(settlement_id);
create index if not exists idx_credit_funding_task_token on credit_funding_events(task_token);
