-- 040 — Black-list de opt-out por cliente.
--
-- Contato que responde uma palavra-gatilho (padrão lógico: "sair"; sem
-- gatilhos cadastrados o server usa a constante — nenhum seed necessário)
-- entra na black-list do dono. Novas campanhas filtram esses números na
-- CRIAÇÃO (todos os caminhos: painel, Multi-BM, API de entrada) e o
-- disparo tem rede de segurança pra campanhas antigas.

CREATE TABLE IF NOT EXISTS client_blacklist_triggers (
  id varchar PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_user_id varchar NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  word varchar(50) NOT NULL,        -- minúscula, sem acentos (normalizada no server)
  created_at timestamptz DEFAULT now(),
  CONSTRAINT client_blacklist_triggers_owner_word_uniq UNIQUE (owner_user_id, word)
);

CREATE TABLE IF NOT EXISTS client_blacklist_contacts (
  id varchar PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_user_id varchar NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  phone_number varchar(20) NOT NULL, -- canônico normalizeBrPhone (55+DDD+9+8)
  origem varchar(20) NOT NULL DEFAULT 'gatilho', -- gatilho | manual
  trigger_word varchar(50),          -- palavra que ativou (origem=gatilho)
  created_at timestamptz DEFAULT now(),
  CONSTRAINT client_blacklist_contacts_owner_phone_uniq UNIQUE (owner_user_id, phone_number)
);

-- Filtro de criação de campanha consulta por dono — o UNIQUE acima já cobre
-- (owner_user_id, phone_number); índice extra não é necessário.
