import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smplayer/providers/player_engine_override_provider.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  const key = 'smplayer.player_engine_override';

  ProviderContainer makeContainer() {
    final c = ProviderContainer();
    addTearDown(c.dispose);
    return c;
  }

  test('默认（无持久化值）build 返回 auto', () async {
    SharedPreferences.setMockInitialValues({});
    final c = makeContainer();
    final value = await c.read(playerEngineOverrideProvider.future);
    expect(value, PlayerEngineOverride.auto);
  });

  test('setOverride(media3) 后 build 返回 media3 且持久化为 name', () async {
    SharedPreferences.setMockInitialValues({});
    final c = makeContainer();
    await c.read(playerEngineOverrideProvider.future);

    await c
        .read(playerEngineOverrideProvider.notifier)
        .setOverride(PlayerEngineOverride.media3);

    expect(
      c.read(playerEngineOverrideProvider).value,
      PlayerEngineOverride.media3,
    );
    final prefs = await SharedPreferences.getInstance();
    expect(prefs.getString(key), 'media3');
  });

  test('持久化值为 media3 时 build 读回 media3', () async {
    SharedPreferences.setMockInitialValues({key: 'media3'});
    final c = makeContainer();
    final value = await c.read(playerEngineOverrideProvider.future);
    expect(value, PlayerEngineOverride.media3);
  });

  test('损坏字符串容错返回 auto', () async {
    SharedPreferences.setMockInitialValues({key: 'garbage-value'});
    final c = makeContainer();
    final value = await c.read(playerEngineOverrideProvider.future);
    expect(value, PlayerEngineOverride.auto);
  });

  test('byName(media3) 不抛', () {
    expect(() => PlayerEngineOverride.values.byName('media3'), returnsNormally);
    expect(
      PlayerEngineOverride.values.byName('media3'),
      PlayerEngineOverride.media3,
    );
  });
}
