-- migrate:up
create table wa_conversation_state (
  tenant_id uuid not null references tenants(id) on delete cascade,
  wa_chat_id text not null,

  state text not null,                 -- IDLE / BUILDING_ORDER / WAITING_PAYMENT
  last_intent text null,
  last_order_id bigint null,

  context jsonb not null default '{}'::jsonb,

  state_updated_at timestamptz not null default now(),
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),

  primary key (tenant_id, wa_chat_id)
);

create index idx_state_tenant_updated
  on wa_conversation_state (tenant_id, updated_at desc);

-- migrate:down
drop table if exists wa_conversation_state;
