import 'package:flutter_test/flutter_test.dart';
import 'package:tane/i18n/strings.g.dart';
import 'package:tane/security/secret_store.dart';
import 'package:tane/services/locale_store.dart';

/// In-memory [SecretStore] for tests.
class FakeSecretStore implements SecretStore {
  final Map<String, String> _data = {};
  @override
  Future<String?> read(String key) async => _data[key];
  @override
  Future<void> write(String key, String value) async => _data[key] = value;
}

void main() {
  // setLocale/useDeviceLocale touch the Flutter locale, which needs a binding.
  TestWidgetsFlutterBinding.ensureInitialized();

  late FakeSecretStore secrets;
  late LocaleStore store;

  setUp(() {
    secrets = FakeSecretStore();
    store = LocaleStore(secrets);
  });

  test('no choice saved yet → follows the device (null)', () async {
    expect(await store.saved(), isNull);
  });

  test('picking Asturian persists it and applies it', () async {
    await store.setLocale(AppLocale.ast);

    expect(await store.saved(), AppLocale.ast);
    expect(LocaleSettings.currentLocale, AppLocale.ast);
    // Asturian is modelled as its real `ast` code so the schema stays honest;
    // Material chrome borrows Spanish elsewhere (see app.dart).
    expect(AppLocale.ast.languageCode, 'ast');
  });

  test('choosing "system language" forgets the explicit choice', () async {
    await store.setLocale(AppLocale.es);
    expect(await store.saved(), AppLocale.es);

    await store.useDeviceLocale();
    expect(await store.saved(), isNull);
  });

  test('an unknown stored tag reads as "follow the device", never throws',
      () async {
    await secrets.write('tane.locale', 'zz-ZZ-removed-in-a-later-build');
    expect(await store.saved(), isNull);
  });
}
