-- Contexta — Channels Migration
-- Run this in your Supabase SQL Editor

-- ── channel_connections table ─────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS channel_connections (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    chatbot_id UUID NOT NULL REFERENCES chatbots(id) ON DELETE CASCADE,
    channel VARCHAR(20) NOT NULL CHECK (channel IN ('telegram', 'whatsapp')),
    bot_token TEXT,
    bot_username TEXT,
    wa_keyword VARCHAR(50),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(chatbot_id, channel)
);
CREATE INDEX IF NOT EXISTS idx_channel_connections_chatbot ON channel_connections(chatbot_id);
CREATE INDEX IF NOT EXISTS idx_channel_connections_wa_keyword ON channel_connections(wa_keyword) WHERE channel = 'whatsapp';
ALTER TABLE channel_connections ENABLE ROW LEVEL SECURITY;
CREATE POLICY "channel_connections_owner" ON channel_connections FOR ALL USING (
    chatbot_id IN (
        SELECT c.id FROM chatbots c
        JOIN companies co ON c.company_id = co.id
        WHERE co.owner_id = auth.uid()
    )
);

-- ── channel_sessions table ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS channel_sessions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    chatbot_id UUID NOT NULL REFERENCES chatbots(id) ON DELETE CASCADE,
    channel VARCHAR(20) NOT NULL,
    external_id TEXT NOT NULL,
    session_id TEXT NOT NULL,
    last_active TIMESTAMPTZ DEFAULT NOW(),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(channel, external_id)
);
CREATE INDEX IF NOT EXISTS idx_channel_sessions_lookup ON channel_sessions(channel, external_id);
ALTER TABLE channel_sessions ENABLE ROW LEVEL SECURITY;
-- Webhook handlers use the service_role key so they bypass RLS.
-- This policy lets authenticated owners read their own sessions via the dashboard.
CREATE POLICY "channel_sessions_owner" ON channel_sessions FOR SELECT USING (
    chatbot_id IN (
        SELECT c.id FROM chatbots c
        JOIN companies co ON c.company_id = co.id
        WHERE co.owner_id = auth.uid()
    )
);
