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

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

class _MockStorage extends Mock implements FlutterSecureStorage {}

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

  test('returns defaults when storage is empty', () async {
    final storage = _MockStorage();
    when(() => storage.read(key: any(named: 'key')))
        .thenAnswer((_) async => null);
    when(() => storage.write(
            key: any(named: 'key'), value: any(named: 'value')))
        .thenAnswer((_) async {});

    final container = ProviderContainer(overrides: [
      secureStorageProvider.overrideWithValue(storage),
    ]);
    addTearDown(container.dispose);

    final s = await container.read(cacheSettingsProvider.future);
    expect(s.likedCapBytes, CacheSettings.defaults.likedCapBytes);
    expect(s.rollingCapBytes, CacheSettings.defaults.rollingCapBytes);
    expect(s.likedCapBytes, 5 * 1024 * 1024 * 1024);
    expect(s.prefetchWindow, 5);
    expect(s.cacheLikedTracks, true);
  });

  test('setPrefetchWindow clamps to 1..10', () async {
    final storage = _MockStorage();
    when(() => storage.read(key: any(named: 'key')))
        .thenAnswer((_) async => null);
    when(() => storage.write(
            key: any(named: 'key'), value: any(named: 'value')))
        .thenAnswer((_) async {});

    final container = ProviderContainer(overrides: [
      secureStorageProvider.overrideWithValue(storage),
    ]);
    addTearDown(container.dispose);

    await container.read(cacheSettingsProvider.future);
    final ctrl = container.read(cacheSettingsProvider.notifier);
    await ctrl.setPrefetchWindow(99);
    expect(container.read(cacheSettingsProvider).value!.prefetchWindow, 10);
    await ctrl.setPrefetchWindow(0);
    expect(container.read(cacheSettingsProvider).value!.prefetchWindow, 1);
  });

  test('setCacheLikedTracks toggles persisted', () async {
    final storage = _MockStorage();
    when(() => storage.read(key: any(named: 'key')))
        .thenAnswer((_) async => null);
    when(() => storage.write(
            key: any(named: 'key'), value: any(named: 'value')))
        .thenAnswer((_) async {});

    final container = ProviderContainer(overrides: [
      secureStorageProvider.overrideWithValue(storage),
    ]);
    addTearDown(container.dispose);

    await container.read(cacheSettingsProvider.future);
    await container.read(cacheSettingsProvider.notifier).setCacheLikedTracks(false);
    expect(
        container.read(cacheSettingsProvider).value!.cacheLikedTracks, false);
    verify(() => storage.write(key: 'cache_liked_tracks', value: 'false'))
        .called(1);
  });
}
