-- V036 - Advanced BI and Report Designer
-- SQLAlchemy creates the portable schema in native mode. PostgreSQL hardening follows.
DO $$ DECLARE t text; BEGIN
  FOREACH t IN ARRAY ARRAY['bi_themes_v036','bi_dashboards_v036','bi_widgets_v036','report_templates_v036','report_renders_v036','bi_share_links_v036'] LOOP
    IF to_regclass(t) IS NOT NULL THEN
      EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',t);
      EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY',t);
      EXECUTE format('DROP POLICY IF EXISTS tenant_isolation_v036 ON %I',t);
      EXECUTE format('CREATE POLICY tenant_isolation_v036 ON %I USING (tenant_id::text = current_setting(''app.current_tenant_id'', true)) WITH CHECK (tenant_id::text = current_setting(''app.current_tenant_id'', true))',t);
    END IF;
  END LOOP;
END $$;
