import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mocktail/mocktail.dart';

import 'package:minstrel/auth/auth_provider.dart';

class _MockStorage extends Mock implements FlutterSecureStorage {}

void main() {
  late _MockStorage storage;

  setUpAll(() {
    registerFallbackValue('');
  });

  setUp(() {
    storage = _MockStorage();
    // Default reads return null; default writes/deletes succeed.
    when(() => storage.read(key: any(named: 'key'))).thenAnswer((_) async => null);
    when(() => storage.write(key: any(named: 'key'), value: any(named: 'value'))).thenAnswer((_) async {});
    when(() => storage.delete(key: any(named: 'key'))).thenAnswer((_) async {});
  });

  test('saves server URL via setServerUrl', () async {
    final container = ProviderContainer(overrides: [
      secureStorageProvider.overrideWithValue(storage),
    ]);
    addTearDown(container.dispose);

    await container.read(authControllerProvider.notifier).setServerUrl('http://localhost:8080');

    verify(() => storage.write(key: 'server_url', value: 'http://localhost:8080')).called(1);
  });

  test('setSession then clearSession transitions auth state to null', () async {
    final container = ProviderContainer(overrides: [
      secureStorageProvider.overrideWithValue(storage),
    ]);
    addTearDown(container.dispose);

    final ctrl = container.read(authControllerProvider.notifier);
    await ctrl.setSession(token: 't', userJson: '{"id":"u","username":"u","is_admin":false}');
    expect((await container.read(authControllerProvider.future))?.username, 'u');

    // clearSession must trigger storage deletes for both keys.
    await ctrl.clearSession();
    verify(() => storage.delete(key: 'session_token')).called(1);
    verify(() => storage.delete(key: 'current_user')).called(1);
    expect(await container.read(authControllerProvider.future), isNull);
  });
}
