-- Organization-owned role configuration cannot be re-parented. Besides being -- a tenant boundary, immutability ensures the deferred default-role invariant -- checks the same Organization before and after an update. CREATE OR REPLACE FUNCTION cph_enforce_agent_role_default() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE target_organization_id TEXT := COALESCE(NEW."organizationId", OLD."organizationId"); active_default_count INTEGER; BEGIN IF TG_OP = 'UPDATE' AND NEW."organizationId" <> OLD."organizationId" THEN RAISE EXCEPTION 'OrganizationAgentRole.organizationId is immutable'; END IF; IF NOT EXISTS (SELECT 1 FROM "Organization" WHERE "id" = target_organization_id) THEN RETURN NULL; END IF; SELECT count(*) INTO active_default_count FROM "OrganizationAgentRole" WHERE "organizationId" = target_organization_id AND "isDefault" = true AND "disabledAt" IS NULL; IF active_default_count <> 1 THEN RAISE EXCEPTION 'Organization % must have exactly one active default Agent role; found %', target_organization_id, active_default_count; END IF; RETURN NULL; END; $$;