-- migrate:up
create table conversation_runs (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references tenants(id) on delete cascade,
  wa_chat_id text not null,
  message_id text not null,

  ts timestamptz not null default now(),
  prev_state text null,
  user_text text null,

  llm_output jsonb null,
  tools jsonb not null default '[]'::jsonb,
  invariants jsonb not null default '{}'::jsonb,

  final_reply text null,
  order_id bigint null,
  payment_link text null,

  status text not null default 'ok', -- ok | warn | error
  error_code text null,
  error_detail text null,
  latency_ms int null,

  unique (tenant_id, message_id)
);

create index idx_runs_tenant_chat_ts
  on conversation_runs (tenant_id, wa_chat_id, ts desc);

-- migrate:down
drop table if exists conversation_runs;
