-- Wever Labs Work Order Execution Binding v1
-- Creates durable records for binding routed Work Orders to operating tool execution.

create table if not exists work_order_execution_bindings (
  id uuid primary key default gen_random_uuid(),
  binding_id text unique not null,
  work_order_id text not null,
  intake_id text,
  task_token text not null,
  tool text not null,
  execution_state text not null default 'bound',
  runtime_record_id text,
  run_contract_id text,
  credit_entitlement_id text,
  provider_confirmation_id text,
  queue_id text,
  result_contract_url text,
  settlement_receipt_url text,
  usage_receipt_url text,
  callback_url text,
  ledger_url text,
  attestation_url text,
  metadata jsonb default '{}'::jsonb,
  created_at timestamptz default now(),
  updated_at timestamptz default now()
);

create table if not exists tool_execution_commands (
  id uuid primary key default gen_random_uuid(),
  command_id text unique not null,
  binding_id text not null references work_order_execution_bindings(binding_id),
  work_order_id text not null,
  task_token text not null,
  tool text not null,
  operation text not null,
  input_refs jsonb default '[]'::jsonb,
  execution_rules jsonb default '[]'::jsonb,
  return_contract jsonb default '{}'::jsonb,
  created_at timestamptz default now()
);

create table if not exists tool_execution_result_events (
  id uuid primary key default gen_random_uuid(),
  event_id text unique not null,
  binding_id text not null,
  work_order_id text not null,
  task_token text not null,
  tool text not null,
  event_type text not null,
  state_after_event text,
  result_contract_url text,
  receipt_url text,
  callback_status text,
  payload jsonb default '{}'::jsonb,
  occurred_at timestamptz default now()
);

create index if not exists idx_work_order_execution_bindings_task_token on work_order_execution_bindings(task_token);
create index if not exists idx_work_order_execution_bindings_work_order on work_order_execution_bindings(work_order_id);
create index if not exists idx_tool_execution_events_task_token on tool_execution_result_events(task_token);
