-- ==========================================================================
-- Agencia PSI — Migracao: Tags de conversa (CRM Grupo 3.1)
-- ==========================================================================
-- Criado por: Leonardo Nohama
-- Data: 2026-04-21 · Sao Carlos/SP — Brasil
--
-- Tags aplicaveis a uma thread de conversa (urgente, primeira consulta,
-- remarcacao, etc). Cada tenant pode criar tags custom alem das padrao.
--
-- Tabelas:
--   - conversation_tags        — definicoes (system com tenant_id NULL + custom)
--   - conversation_thread_tags — join (tenant_id, thread_key, tag_id)
--
-- thread_key: mesma logica de conversation_threads
--   - '<uuid>'       → thread de paciente
--   - 'anon:<phone>' → thread anonima
-- ==========================================================================

-- ---------------------------------------------------------------------------
-- Tabela: conversation_tags (definicoes)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.conversation_tags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID REFERENCES public.tenants(id) ON DELETE CASCADE,  -- NULL = system tag
    name TEXT NOT NULL CHECK (length(name) > 0 AND length(name) <= 40),
    slug TEXT NOT NULL CHECK (slug ~ '^[a-z0-9_-]{1,40}$'),
    color TEXT NOT NULL DEFAULT '#6366f1' CHECK (color ~ '^#[0-9a-fA-F]{6}$'),
    icon TEXT,  -- classe de icone primeicons (ex: 'pi pi-exclamation-triangle')
    position INT NOT NULL DEFAULT 100,
    is_system BOOLEAN NOT NULL DEFAULT false,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Unique: (tenant_id, slug). Para tenant_id NULL (system), um indice parcial separado.
CREATE UNIQUE INDEX IF NOT EXISTS uq_conv_tags_tenant_slug
    ON public.conversation_tags (tenant_id, slug)
    WHERE tenant_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS uq_conv_tags_system_slug
    ON public.conversation_tags (slug)
    WHERE tenant_id IS NULL;

CREATE INDEX IF NOT EXISTS idx_conv_tags_tenant
    ON public.conversation_tags (tenant_id, position);

DROP TRIGGER IF EXISTS trg_conv_tags_updated_at ON public.conversation_tags;
CREATE TRIGGER trg_conv_tags_updated_at
    BEFORE UPDATE ON public.conversation_tags
    FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();

COMMENT ON TABLE public.conversation_tags IS
    'Definicoes de tags aplicaveis a threads. tenant_id NULL = tag do sistema (todos veem).';

-- ---------------------------------------------------------------------------
-- Tabela: conversation_thread_tags (join many-to-many)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS public.conversation_thread_tags (
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
    thread_key TEXT NOT NULL,
    tag_id UUID NOT NULL REFERENCES public.conversation_tags(id) ON DELETE CASCADE,
    tagged_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
    tagged_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (tenant_id, thread_key, tag_id)
);

CREATE INDEX IF NOT EXISTS idx_conv_thread_tags_tenant_thread
    ON public.conversation_thread_tags (tenant_id, thread_key);

CREATE INDEX IF NOT EXISTS idx_conv_thread_tags_tag
    ON public.conversation_thread_tags (tag_id);

COMMENT ON TABLE public.conversation_thread_tags IS
    'Join de tags aplicadas a cada thread de conversa.';

-- ---------------------------------------------------------------------------
-- Seed de tags padrao (system)
-- ---------------------------------------------------------------------------
INSERT INTO public.conversation_tags (tenant_id, name, slug, color, icon, position, is_system)
VALUES
    (NULL, 'Urgente',          'urgente',          '#ef4444', 'pi pi-exclamation-triangle', 10, true),
    (NULL, 'Primeira consulta','primeira-consulta','#0ea5e9', 'pi pi-user-plus',            20, true),
    (NULL, 'Remarcação',       'remarcacao',       '#f59e0b', 'pi pi-calendar-times',       30, true),
    (NULL, 'Confirmada',       'confirmada',       '#22c55e', 'pi pi-check-circle',         40, true),
    (NULL, 'Follow-up',        'follow-up',        '#a855f7', 'pi pi-reply',                50, true)
ON CONFLICT DO NOTHING;

-- ---------------------------------------------------------------------------
-- RLS: conversation_tags
-- ---------------------------------------------------------------------------
ALTER TABLE public.conversation_tags ENABLE ROW LEVEL SECURITY;

-- SELECT: system tags (tenant_id NULL) = todos; custom = membros ativos do tenant
DROP POLICY IF EXISTS "conv_tags: select" ON public.conversation_tags;
CREATE POLICY "conv_tags: select"
    ON public.conversation_tags
    FOR SELECT
    TO authenticated
    USING (
        tenant_id IS NULL
        OR public.is_saas_admin()
        OR EXISTS (
            SELECT 1 FROM public.tenant_members tm
            WHERE tm.user_id = auth.uid()
              AND tm.tenant_id = conversation_tags.tenant_id
              AND tm.status = 'active'
        )
    );

-- INSERT: membros ativos do tenant criam custom. Nao podem criar system (tenant_id NULL)
DROP POLICY IF EXISTS "conv_tags: insert custom" ON public.conversation_tags;
CREATE POLICY "conv_tags: insert custom"
    ON public.conversation_tags
    FOR INSERT
    TO authenticated
    WITH CHECK (
        tenant_id IS NOT NULL
        AND is_system = false
        AND (
            public.is_saas_admin()
            OR EXISTS (
                SELECT 1 FROM public.tenant_members tm
                WHERE tm.user_id = auth.uid()
                  AND tm.tenant_id = conversation_tags.tenant_id
                  AND tm.status = 'active'
            )
        )
    );

-- UPDATE: tenant members para tags proprias (custom). Sistema bloqueado.
DROP POLICY IF EXISTS "conv_tags: update custom" ON public.conversation_tags;
CREATE POLICY "conv_tags: update custom"
    ON public.conversation_tags
    FOR UPDATE
    TO authenticated
    USING (
        is_system = false
        AND tenant_id IS NOT NULL
        AND (
            public.is_saas_admin()
            OR EXISTS (
                SELECT 1 FROM public.tenant_members tm
                WHERE tm.user_id = auth.uid()
                  AND tm.tenant_id = conversation_tags.tenant_id
                  AND tm.status = 'active'
            )
        )
    )
    WITH CHECK (is_system = false);

-- DELETE: tenant members removem tags custom. Sistema bloqueado.
DROP POLICY IF EXISTS "conv_tags: delete custom" ON public.conversation_tags;
CREATE POLICY "conv_tags: delete custom"
    ON public.conversation_tags
    FOR DELETE
    TO authenticated
    USING (
        is_system = false
        AND tenant_id IS NOT NULL
        AND (
            public.is_saas_admin()
            OR EXISTS (
                SELECT 1 FROM public.tenant_members tm
                WHERE tm.user_id = auth.uid()
                  AND tm.tenant_id = conversation_tags.tenant_id
                  AND tm.status = 'active'
            )
        )
    );

-- ---------------------------------------------------------------------------
-- RLS: conversation_thread_tags
-- ---------------------------------------------------------------------------
ALTER TABLE public.conversation_thread_tags ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "conv_thread_tags: select" ON public.conversation_thread_tags;
CREATE POLICY "conv_thread_tags: select"
    ON public.conversation_thread_tags
    FOR SELECT
    TO authenticated
    USING (
        public.is_saas_admin()
        OR EXISTS (
            SELECT 1 FROM public.tenant_members tm
            WHERE tm.user_id = auth.uid()
              AND tm.tenant_id = conversation_thread_tags.tenant_id
              AND tm.status = 'active'
        )
    );

DROP POLICY IF EXISTS "conv_thread_tags: insert" ON public.conversation_thread_tags;
CREATE POLICY "conv_thread_tags: insert"
    ON public.conversation_thread_tags
    FOR INSERT
    TO authenticated
    WITH CHECK (
        tagged_by = auth.uid()
        AND (
            public.is_saas_admin()
            OR EXISTS (
                SELECT 1 FROM public.tenant_members tm
                WHERE tm.user_id = auth.uid()
                  AND tm.tenant_id = conversation_thread_tags.tenant_id
                  AND tm.status = 'active'
            )
        )
    );

DROP POLICY IF EXISTS "conv_thread_tags: delete" ON public.conversation_thread_tags;
CREATE POLICY "conv_thread_tags: delete"
    ON public.conversation_thread_tags
    FOR DELETE
    TO authenticated
    USING (
        public.is_saas_admin()
        OR EXISTS (
            SELECT 1 FROM public.tenant_members tm
            WHERE tm.user_id = auth.uid()
              AND tm.tenant_id = conversation_thread_tags.tenant_id
              AND tm.status = 'active'
        )
    );

-- ==========================================================================
-- FIM DA MIGRACAO
-- ==========================================================================
