-- V033 Corporate Operating System & Digital Twin
-- SQLAlchemy creates the tables in native/SQLite mode. PostgreSQL production adds RLS below.
DO $$
DECLARE t text;
BEGIN
  FOREACH t IN ARRAY ARRAY['corporate_units_v033','corporate_processes_v033','corporate_assets_v033','strategic_objectives_v033','key_results_v033','operating_kpis_v033','digital_twin_relations_v033','operating_recommendations_v033'] 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_v033 ON %I',t);
      EXECUTE format('CREATE POLICY tenant_isolation_v033 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 $$;
