import { resolvePermissions, type PermissionKey, type PermissionOverrides, SystemRole } from "@capakraken/shared";
import {
  canonicalizeSseAudiences,
  permissionAudience,
  resourceAudience,
  type SseAudience,
  type SseSubscriptionOptions,
  userAudience,
} from "./event-bus.js";

export interface SseSubscriberIdentity {
  userId: string;
  systemRole: SystemRole;
  permissionOverrides?: PermissionOverrides | null;
  resourceId?: string | null;
}

export interface DerivedSseSubscription extends SseSubscriptionOptions {
  audiences: SseAudience[];
  permissions: Set<PermissionKey>;
  includeUnscoped: false;
}

export function deriveUserSseSubscription(
  identity: SseSubscriberIdentity,
  roleDefaults?: Record<string, PermissionKey[]>,
): DerivedSseSubscription {
  const permissions = resolvePermissions(
    identity.systemRole,
    identity.permissionOverrides ?? null,
    roleDefaults,
  );

  return {
    audiences: canonicalizeSseAudiences([
      userAudience(identity.userId),
      ...(identity.resourceId ? [resourceAudience(identity.resourceId)] : []),
      ...Array.from(permissions, (permission) => permissionAudience(permission)),
    ]),
    permissions,
    includeUnscoped: false,
  };
}
