-- =============================================================================
-- F5 — Trigger que re-expõe schemas tenant no PostgREST a cada clone/drop
--
-- public.refresh_pgrst_schemas() (criada em manual/f5_pgrst_refresh_schemas.
-- supabase_admin.sql, owned por supabase_admin) seta pgrst.db_schemas + NOTIFY.
-- Este trigger em tenant_schemas a dispara automaticamente — clone_tenant_template
-- e drop_tenant_schema NÃO precisam ser tocados (eles inserem/removem em
-- tenant_schemas, o que aciona o refresh no COMMIT).
--
-- PRÉ-REQUISITO: aplicar f5_pgrst_refresh_schemas.supabase_admin.sql ANTES desta
-- migration (a função precisa existir e estar owned por supabase_admin).
-- =============================================================================

BEGIN;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
        WHERE n.nspname = 'public' AND p.proname = 'refresh_pgrst_schemas'
    ) THEN
        RAISE EXCEPTION 'F5: public.refresh_pgrst_schemas() não existe — aplique manual/f5_pgrst_refresh_schemas.supabase_admin.sql primeiro';
    END IF;
END $$;

-- Trigger function (owned por postgres) só delega pro refresh (SECDEF supabase_admin)
CREATE OR REPLACE FUNCTION public.trg_refresh_pgrst_schemas()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public', 'pg_temp'
AS $$
BEGIN
    PERFORM public.refresh_pgrst_schemas();
    RETURN NULL;
END;
$$;

DROP TRIGGER IF EXISTS trg_tenant_schemas_pgrst_refresh ON public.tenant_schemas;
CREATE TRIGGER trg_tenant_schemas_pgrst_refresh
    AFTER INSERT OR DELETE OR UPDATE OF schema_name ON public.tenant_schemas
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.trg_refresh_pgrst_schemas();

COMMIT;
