CREATE TABLE IF NOT EXISTS sales_external_links (
  id BIGSERIAL PRIMARY KEY,
  link_id TEXT NOT NULL UNIQUE,
  tenant_id TEXT NOT NULL,
  deal_id TEXT NOT NULL,
  communication_id TEXT,
  sales_call_id TEXT,
  channel_provider TEXT NOT NULL,
  external_thread_id TEXT,
  external_chat_id TEXT,
  external_call_id TEXT,
  voice_session_id TEXT,
  ai_session_id TEXT,
  interaction_id TEXT,
  customer_id TEXT,
  phone_number TEXT,
  external_status TEXT,
  link_metadata_json TEXT NOT NULL DEFAULT '{}',
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  last_sync_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_sales_external_links_deal_sync ON sales_external_links(deal_id, last_sync_at);
CREATE INDEX IF NOT EXISTS idx_sales_external_links_thread ON sales_external_links(external_thread_id);
CREATE INDEX IF NOT EXISTS idx_sales_external_links_voice_session ON sales_external_links(voice_session_id);
CREATE INDEX IF NOT EXISTS idx_sales_external_links_external_call ON sales_external_links(external_call_id);
CREATE INDEX IF NOT EXISTS idx_sales_external_links_interaction ON sales_external_links(interaction_id);
CREATE INDEX IF NOT EXISTS idx_sales_external_links_customer_phone ON sales_external_links(customer_id, phone_number);
