SELECT json_build_object(
  'schemaVersion','core-hub.migration.v1',
  'source','inter-hub-production',
  'exportedAt', now(),
  'records', json_build_object(
    'hubs', COALESCE((SELECT json_agg(json_build_object('id',id,'slug',slug,'name',name,'domain',domain,'hubKind',hub_kind,'hubFamily',hub_family,'vsmFunction',vsm_function,'vsmSystem',vsm_system,'status','active')) FROM hubs), '[]'::json),
    'hubCapabilityManifests', COALESCE((SELECT json_agg(json_build_object('id',id,'hubId',hub_id,'manifestVersion',manifest_version,'declaredWidgetTypes',declared_widget_types,'declaredEventTypes',declared_event_types,'declaredAnnotationCategories',declared_annotation_categories,'declaredPolicyScopes',declared_policy_scopes,'status',status,'capabilityDescription',capability_description,'contact',contact,'activatedAt',activated_at)) FROM hub_capability_manifests), '[]'::json),
    'apiConsumers', COALESCE((SELECT json_agg(json_build_object('id',id,'name',name,'description',description,'hubCapabilityManifestId',hub_capability_manifest_id,'rateLimitPerMinute',rate_limit_per_minute,'quotaPerDay',quota_per_day,'isActive',is_active)) FROM api_consumers), '[]'::json),
    'apiKeys', COALESCE((SELECT json_agg(json_build_object('id',id,'apiConsumerId',api_consumer_id,'keyPrefix',key_prefix,'keyHash',key_hash,'scopes',scopes,'tokenType',token_type,'expiresAt',expires_at,'revokedAt',revoked_at)) FROM api_keys), '[]'::json),
    'widgets', COALESCE((SELECT json_agg(json_build_object('id',id,'hubId',hub_id,'name',name,'widgetType',widget_type,'capabilityRef',capability_ref,'viewContext',view_context,'policyScope',policy_scope,'status',status,'version',version,'isArchived',is_archived)) FROM widgets), '[]'::json),
    'interactionEvents', COALESCE((SELECT json_agg(json_build_object('id',id,'widgetId',widget_id,'eventType',event_type,'viewContext',view_context_ref,'actorId',actor_id,'actorType',actor_type,'metadata',metadata,'occurredAt',occurred_at)) FROM interaction_events), '[]'::json)
  )
);
