import 'dart:async'; import 'package:drift/drift.dart' show Value; import 'package:drift/native.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:plezy/connection/connection.dart'; import 'package:plezy/connection/connection_registry.dart'; import 'package:plezy/database/app_database.dart'; import 'package:plezy/models/plex/plex_home_user.dart'; import 'package:plezy/profiles/active_profile_provider.dart'; import 'package:plezy/profiles/plex_home_service.dart'; import 'package:plezy/profiles/profile.dart'; import 'package:plezy/profiles/profile_connection.dart'; import 'package:plezy/profiles/profile_connection_registry.dart'; import 'package:plezy/profiles/profile_registry.dart'; import 'package:plezy/services/storage_service.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import '../test_helpers/prefs.dart'; final class _RecordingPreferencesPlatform extends SharedPreferencesAsyncPlatform { _RecordingPreferencesPlatform(this.delegate); final SharedPreferencesAsyncPlatform delegate; final List writes = []; String? failIntKey; @override Future setString(String key, String value, SharedPreferencesOptions options) async { writes.add('string:$key'); await delegate.setString(key, value, options); } @override Future setInt(String key, int value, SharedPreferencesOptions options) async { writes.add('int:$key'); if (key == failIntKey) throw StateError('injected recency failure'); await delegate.setInt(key, value, options); } @override Future setBool(String key, bool value, SharedPreferencesOptions options) => delegate.setBool(key, value, options); @override Future setDouble(String key, double value, SharedPreferencesOptions options) => delegate.setDouble(key, value, options); @override Future setStringList(String key, List value, SharedPreferencesOptions options) => delegate.setStringList(key, value, options); @override Future getString(String key, SharedPreferencesOptions options) => delegate.getString(key, options); @override Future getBool(String key, SharedPreferencesOptions options) => delegate.getBool(key, options); @override Future getDouble(String key, SharedPreferencesOptions options) => delegate.getDouble(key, options); @override Future getInt(String key, SharedPreferencesOptions options) => delegate.getInt(key, options); @override Future?> getStringList(String key, SharedPreferencesOptions options) => delegate.getStringList(key, options); @override Future clear(ClearPreferencesParameters parameters, SharedPreferencesOptions options) => delegate.clear(parameters, options); @override Future> getPreferences(GetPreferencesParameters parameters, SharedPreferencesOptions options) => delegate.getPreferences(parameters, options); @override Future> getKeys(GetPreferencesParameters parameters, SharedPreferencesOptions options) => delegate.getKeys(parameters, options); } PlexHomeUser _homeUser(String uuid, {int id = 1, String name = 'Home User', String thumb = ''}) { return PlexHomeUser( id: id, uuid: uuid, title: name, thumb: thumb, hasPassword: false, restricted: false, updatedAt: null, admin: true, guest: false, protected: false, ); } PlexAccountConnection _account(String id) { return PlexAccountConnection( id: id, accountToken: 'token-$id', clientIdentifier: 'client-$id', accountLabel: 'Plex', createdAt: DateTime(2026, 1, 1), ); } JellyfinConnection _jellyfin(String id, {required DateTime createdAt, required String primaryImageTag}) { return JellyfinConnection( id: id, baseUrl: 'https://jellyfin.example', serverName: 'Jellyfin', serverMachineId: 'machine-$id', userId: 'user-$id', userName: 'User $id', accessToken: 'token-$id', deviceId: 'device-$id', primaryImageTag: primaryImageTag, createdAt: createdAt, ); } void main() { late AppDatabase db; late ProfileRegistry registry; late ConnectionRegistry connections; late ProfileConnectionRegistry profileConnections; late PlexHomeService plexHome; late ActiveProfileProvider provider; late StorageService storage; late _RecordingPreferencesPlatform preferencesPlatform; late List fetchedHomeUsers; setUp(() async { resetSharedPreferencesForTest(); preferencesPlatform = _RecordingPreferencesPlatform(SharedPreferencesAsyncPlatform.instance!); SharedPreferencesAsyncPlatform.instance = preferencesPlatform; db = AppDatabase.forTesting(NativeDatabase.memory()); registry = ProfileRegistry(db); connections = ConnectionRegistry(db); storage = await StorageService.getInstance(); fetchedHomeUsers = const []; profileConnections = ProfileConnectionRegistry(db); plexHome = PlexHomeService( connections: connections, profileConnections: profileConnections, storage: storage, plexHomeUserFetcher: (_) async => fetchedHomeUsers, ); provider = ActiveProfileProvider( registry: registry, plexHome: plexHome, connections: connections, profileConnections: profileConnections, storage: storage, ); }); tearDown(() async { await provider.resetForTesting(); provider.dispose(); await plexHome.dispose(); await db.close(); }); group('ActiveProfileProvider', () { test('initialize with no profiles leaves active null', () async { await provider.initialize(); expect(provider.profiles, isEmpty); expect(provider.active, isNull); }); test('concurrent initialize calls await the same in-flight load', () async { final first = provider.initialize(); final second = provider.initialize(); expect(identical(first, second), isTrue); await second; expect(provider.isInitialized, isTrue); }); test('initialize leaves active null when no active id stored', () async { // Fresh state: no auto-fallback to the first profile so the UI can // force the picker. The binder skips its rebind while active is null, // which is what avoids the surprise PIN prompt at first sign-in. await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await provider.initialize(); expect(provider.profiles, hasLength(1)); expect(provider.activeId, isNull); }); test('reloadFromStorage resolves Plex Home profile added after early initialize', () async { await provider.initialize(); expect(provider.profiles, isEmpty); final account = _account('plex.migrated'); final user = _homeUser('home-user-1', name: 'Migrated User'); fetchedHomeUsers = [user]; await connections.upsert(account); await storage.savePlexHomeUsersCache(account.id, [user.toJson()]); final profileId = plexHomeProfileId(accountConnectionId: account.id, homeUserUuid: user.uuid); await storage.setActiveProfileId(profileId); await provider.reloadFromStorage(); expect(provider.profiles.map((p) => p.id), contains(profileId)); expect(provider.activeId, profileId); expect(provider.active?.displayName, 'Migrated User'); }); test('initialize keeps a stored id it cannot resolve (transient snapshots must not wipe it)', () async { // Early snapshots can legitimately miss state (boot before migration, // Plex Home cache not hydrated yet) — resolution goes inactive but the // persisted selection survives for a later snapshot to resolve. // Genuinely unresolvable ids are cleared by the boot guard and the // post-removal settle flow, not here. await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await storage.setActiveProfileId('ghost-id-no-longer-exists'); await provider.initialize(); await Future.delayed(Duration.zero); expect(provider.activeId, isNull); expect(storage.getActiveProfileId(), 'ghost-id-no-longer-exists'); }); test('re-upserting an identical connection does not notify listeners', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); final account = _account('plex.acct'); await connections.upsert(account); await provider.initialize(); await Future.delayed(const Duration(milliseconds: 20)); var notifications = 0; provider.addListener(() => notifications++); // Same row content — the binder does this on every successful bind // (persisting refreshed-but-identical server metadata). await connections.upsert(account); await Future.delayed(const Duration(milliseconds: 20)); expect(notifications, 0); }); group('avatarUrlFor', () { test('returns the linked Jellyfin user picture after initialize', () async { final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)); final connection = _jellyfin('first', createdAt: DateTime(2025, 1, 1), primaryImageTag: 'avatar-tag'); await registry.upsert(profile); await connections.upsert(connection); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'first', userIdentifier: 'user-first'), ); await provider.initialize(); expect( provider.avatarUrlFor(profile.id), 'https://jellyfin.example/Users/user-first/Images/Primary' '?tag=avatar-tag&maxWidth=240&maxHeight=240', ); }); test('returns null for profiles without links and unknown profile ids', () async { await registry.upsert(Profile.local(id: 'unlinked', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await provider.initialize(); expect(provider.avatarUrlFor('unlinked'), isNull); expect(provider.avatarUrlFor('unknown'), isNull); }); test('linking an older connection updates the selected picture', () async { final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)); final newer = _jellyfin('newer', createdAt: DateTime(2026, 1, 2), primaryImageTag: 'newer-tag'); final older = _jellyfin('older', createdAt: DateTime(2025, 12, 31), primaryImageTag: 'older-tag'); await registry.upsert(profile); await connections.upsert(newer); await connections.upsert(older); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'newer', userIdentifier: 'user-newer'), ); await provider.initialize(); expect( provider.avatarUrlFor(profile.id), 'https://jellyfin.example/Users/user-newer/Images/Primary' '?tag=newer-tag&maxWidth=240&maxHeight=240', ); final changed = Completer(); void listener() { if (provider.avatarUrlFor(profile.id)?.contains('older-tag') ?? false) { if (!changed.isCompleted) changed.complete(); } } provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'older', userIdentifier: 'user-older'), ); await changed.future.timeout(const Duration(seconds: 2)); expect( provider.avatarUrlFor(profile.id), 'https://jellyfin.example/Users/user-older/Images/Primary' '?tag=older-tag&maxWidth=240&maxHeight=240', ); }); test('a corrected connection creation time re-picks the avatar without a restart', () async { // createdAt is a real column, not part of toConfigJson, so the // connection diff guard has to compare it explicitly. Nothing in // normal operation rewrites it — ConnectionRegistry pins creation // order across re-auth — but a restore or a backfill can, and // swallowing that would leave a stale avatar until the next launch. final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)); await registry.upsert(profile); await connections.upsert(_jellyfin('a', createdAt: DateTime(2025, 1, 1), primaryImageTag: 'a-tag')); await connections.upsert(_jellyfin('b', createdAt: DateTime(2026, 1, 1), primaryImageTag: 'b-tag')); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'a', userIdentifier: 'user-a'), ); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'b', userIdentifier: 'user-b'), ); await provider.initialize(); expect(provider.avatarUrlFor(profile.id), contains('tag=a-tag')); final changed = Completer(); void listener() { if ((provider.avatarUrlFor(profile.id)?.contains('b-tag') ?? false) && !changed.isCompleted) { changed.complete(); } } provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); // Straight to the table: the registry deliberately refuses to restamp // an existing row, so this stands in for an out-of-band correction. await (db.update(db.connections)..where((t) => t.id.equals('a'))).write( ConnectionsCompanion(createdAt: Value(DateTime(2027, 1, 1).millisecondsSinceEpoch)), ); await changed.future.timeout(const Duration(seconds: 2)); expect(provider.avatarUrlFor(profile.id), contains('tag=b-tag')); }); test('token and timestamp churn on a link does not notify listeners', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await connections.upsert(_jellyfin('jellyfin', createdAt: DateTime(2025, 1, 1), primaryImageTag: 'avatar-tag')); await profileConnections.upsert( const ProfileConnection( profileId: 'p1', connectionId: 'jellyfin', userToken: 'initial-token', userIdentifier: 'user-jellyfin', ), ); await provider.initialize(); var notifications = 0; void listener() => notifications++; provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); final churnObserved = Completer(); final rowSubscription = profileConnections.watchAll().listen((rows) { final row = rows.single; if (row.userToken == 'refreshed-token' && row.tokenAcquiredAt != null && !churnObserved.isCompleted) { churnObserved.complete(); } }); addTearDown(rowSubscription.cancel); await profileConnections.recordToken('p1', 'jellyfin', 'refreshed-token'); await churnObserved.future.timeout(const Duration(seconds: 2)); await Future(() {}); expect(notifications, 0); }); test('changing a Plex link user changes the picture and notifies listeners', () async { final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)); final account = _account('plex.acct'); final firstUser = _homeUser('home-1', thumb: 'https://images.example/first.jpg'); final secondUser = _homeUser('home-2', id: 2, thumb: 'https://images.example/second.jpg'); fetchedHomeUsers = [firstUser, secondUser]; await registry.upsert(profile); await connections.upsert(account); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'plex.acct', userIdentifier: 'home-1'), ); expect(await plexHome.refresh(account), isTrue); await provider.initialize(); expect(provider.avatarUrlFor(profile.id), firstUser.thumb); var notifications = 0; final changed = Completer(); void listener() { notifications++; if (provider.avatarUrlFor(profile.id) == secondUser.thumb && !changed.isCompleted) { changed.complete(); } } provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); await profileConnections.upsert( const ProfileConnection(profileId: 'p1', connectionId: 'plex.acct', userIdentifier: 'home-2'), ); await changed.future.timeout(const Duration(seconds: 2)); expect(provider.avatarUrlFor(profile.id), secondUser.thumb); expect(notifications, greaterThan(0)); }); }); test('initialize resolves the stored active profile id', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await storage.setActiveProfileId('p2'); await provider.initialize(); expect(provider.activeId, 'p2'); }); test('activate without PIN switches a non-protected profile', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await provider.initialize(); final p2 = provider.profiles.firstWhere((p) => p.id == 'p2'); final ok = await provider.activate(p2); expect(ok, isTrue); expect(provider.activeId, 'p2'); }); test('recency failure leaves stored and in-memory active identity unchanged', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await storage.setActiveProfileId('p1'); await provider.initialize(); preferencesPlatform.writes.clear(); preferencesPlatform.failIntKey = 'profile_last_used_p2'; final p2 = provider.profiles.firstWhere((profile) => profile.id == 'p2'); await expectLater(provider.activate(p2), throwsA(isA())); await storage.prefs.reloadCache(); expect(preferencesPlatform.writes, ['int:profile_last_used_p2']); expect(storage.getProfileLastUsed('p2'), isNull); expect(storage.getActiveProfileId(), 'p1'); expect(provider.activeId, 'p1'); }); test('activation persists recency then marker before notifying listeners', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await storage.setActiveProfileId('p1'); await provider.initialize(); preferencesPlatform.writes.clear(); var notifiedAfterCommit = false; void listener() { if (provider.activeId != 'p2') return; notifiedAfterCommit = storage.getProfileLastUsed('p2') != null && storage.getActiveProfileId() == 'p2' && preferencesPlatform.writes.length >= 2 && preferencesPlatform.writes[0] == 'int:profile_last_used_p2' && preferencesPlatform.writes[1] == 'string:active_app_profile_id'; } provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); final p2 = provider.profiles.firstWhere((profile) => profile.id == 'p2'); expect(await provider.activate(p2), isTrue); expect(preferencesPlatform.writes.take(2), ['int:profile_last_used_p2', 'string:active_app_profile_id']); expect(notifiedAfterCommit, isTrue); }); test('activate moves the selected profile to the front by recent usage', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await provider.initialize(); expect(provider.profiles.map((p) => p.id).toList(), ['p1', 'p2']); final p2 = provider.profiles.firstWhere((p) => p.id == 'p2'); final ok = await provider.activate(p2); expect(ok, isTrue); expect(provider.profiles.map((p) => p.id).toList(), ['p2', 'p1']); expect(storage.getProfileLastUsed('p2'), isNotNull); }); test('clearActiveProfile clears storage and in-memory active profile', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await provider.initialize(); await provider.activate(provider.profiles.single); await provider.clearActiveProfile(); expect(storage.getActiveProfileId(), isNull); expect(provider.active, isNull); }); test('activate rejects wrong PIN for a protected local profile', () async { await registry.upsert( Profile.local(id: 'p1', displayName: 'Kids', pinHash: computePinHash('1234'), createdAt: DateTime(2026, 1, 1)), ); await provider.initialize(); final p1 = provider.profiles.first; expect(await provider.activate(p1, pin: 'wrong'), isFalse); expect(await provider.activate(p1, pin: '1234'), isTrue); }); test('hasMultipleProfiles reflects the registry size', () async { await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1))); await provider.initialize(); expect(provider.hasMultipleProfiles, isFalse); // Latch onto the next provider notification that flips the flag, // instead of sleeping a fixed duration. The provider is a ChangeNotifier // (not a Stream), so we use addListener + Completer here rather than // expectLater(stream, ...) like the other profile tests. final flipped = Completer(); void listener() { if (provider.hasMultipleProfiles && !flipped.isCompleted) { flipped.complete(); } } provider.addListener(listener); addTearDown(() => provider.removeListener(listener)); await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2))); await flipped.future.timeout(const Duration(seconds: 2)); expect(provider.hasMultipleProfiles, isTrue); }); }); }