import { inject, InjectionToken, Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { AuthService } from '@core/auth';
import { map } from 'rxjs';

export const USER_SUB = new InjectionToken<Signal<string>>(
  'core.storage.user-sub',
  {
    factory: () => {
      const auth = inject(AuthService);
      return toSignal(
        auth.authenticated$.pipe(
          // Map to user sub or 'anonymous' if not authenticated
          // This ensures that the signal updates when authentication state changes
          map(() => auth.getClaimByKey('sub') ?? 'anonymous'),
        ),
      );
    },
  },
);

export function provideUserSubFactory(factory: () => Signal<string>) {
  return { provide: USER_SUB, useFactory: factory };
}
