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

  provider text not null,          -- sim / evolution / twilio
  message_id text not null,        -- idempotencia por provider
  direction text not null,         -- in / out

  ts timestamptz not null default now(),
  text text null,
  payload jsonb not null default '{}'::jsonb,

  run_id uuid null,

  unique (tenant_id, provider, message_id)
);

create index idx_msgs_tenant_chat_ts
  on wa_messages (tenant_id, wa_chat_id, ts desc);

-- migrate:down
drop table if exists wa_messages;
