-- 052 — Trilha B: endurecimento do canal Texto (RCS + SMS).
--
-- rcs_event_queue: callbacks MKOM brutos persistidos (antes: processados
-- inline e logados truncados — irreprocessável). Webhook valida token,
-- enfileira e responde 200; worker normaliza com retry (5 tentativas).
-- sms_messages: outbox do fornecedor SMS (EM ABERTO — interface pronta).

CREATE TABLE IF NOT EXISTS rcs_event_queue (
  id bigserial PRIMARY KEY,
  endpoint varchar(10) NOT NULL,          -- status | reply | events
  payload jsonb NOT NULL,                 -- corpo BRUTO do callback MKOM
  status varchar(12) NOT NULL DEFAULT 'pending',
  attempt_count integer NOT NULL DEFAULT 0,
  last_error text,
  created_at timestamptz DEFAULT now(),
  processed_at timestamptz
);
CREATE INDEX IF NOT EXISTS idx_rcs_event_queue_status ON rcs_event_queue (status, id);

CREATE TABLE IF NOT EXISTS sms_messages (
  id varchar PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_user_id varchar NOT NULL,
  service_id varchar,
  campaign_id varchar,
  vendor varchar(30) NOT NULL,
  vendor_message_id varchar,
  reference_id varchar,
  phone varchar(20) NOT NULL,             -- canônico normalizeBrPhone
  text text NOT NULL,
  status varchar(20) NOT NULL DEFAULT 'PENDING_SEND',
  error_message text,
  sent_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_sms_messages_phone ON sms_messages (phone);
CREATE INDEX IF NOT EXISTS idx_sms_messages_status_sent ON sms_messages (status, sent_at);
