import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:smplayer/core/contracts/script_widget.dart';
import 'package:smplayer/core/infra/storage/json_script_widget_repository.dart';

void main() {
  test('模块与订阅可以跨仓储实例持久化并按标题排序', () async {
    final temporaryDirectory = await Directory.systemTemp.createTemp(
      'smplayer-script-widget-repository-',
    );
    addTearDown(() => temporaryDirectory.delete(recursive: true));
    final repositoryFile = File(
      '${temporaryDirectory.path}${Platform.pathSeparator}widgets.json',
    );
    final repository = JsonScriptWidgetRepository(file: repositoryFile);
    final timestamp = DateTime.utc(2026, 7, 12);

    await repository.upsertWidget(
      _installedWidget(id: 'zeta', title: '最后', timestamp: timestamp),
    );
    await repository.upsertWidget(
      _installedWidget(id: 'alpha', title: '开头', timestamp: timestamp),
    );
    await repository.upsertSubscription(
      ScriptWidgetSubscription(
        url: 'https://example.com/catalog.fwd',
        catalog: const ScriptWidgetCatalog(
          title: '示例订阅',
          widgets: <ScriptWidgetCatalogEntry>[
            ScriptWidgetCatalogEntry(
              id: 'alpha',
              title: '开头',
              url: 'https://example.com/alpha.js',
            ),
          ],
        ),
        refreshedAt: timestamp,
      ),
    );

    final reloadedRepository = JsonScriptWidgetRepository(file: repositoryFile);
    final widgets = await reloadedRepository.listWidgets();
    final subscriptions = await reloadedRepository.listSubscriptions();

    expect(widgets.map((widget) => widget.manifest.id), <String>[
      'alpha',
      'zeta',
    ]);
    expect(subscriptions.single.catalog.title, '示例订阅');
    expect(
      subscriptions.single.catalog.widgets.single.url,
      'https://example.com/alpha.js',
    );
  });

  test('损坏的仓储文件安全降级为空状态', () async {
    final temporaryDirectory = await Directory.systemTemp.createTemp(
      'smplayer-script-widget-corrupt-',
    );
    addTearDown(() => temporaryDirectory.delete(recursive: true));
    final repositoryFile = File(
      '${temporaryDirectory.path}${Platform.pathSeparator}widgets.json',
    );
    await repositoryFile.writeAsString('{not valid json');

    final repository = JsonScriptWidgetRepository(file: repositoryFile);

    expect(await repository.listWidgets(), isEmpty);
    expect(await repository.listSubscriptions(), isEmpty);
  });
}

InstalledScriptWidget _installedWidget({
  required String id,
  required String title,
  required DateTime timestamp,
}) {
  return InstalledScriptWidget(
    manifest: ScriptWidgetManifest(id: id, title: title),
    scriptSource: 'const WidgetMetadata = { id: "$id", title: "$title" };',
    installedAt: timestamp,
    updatedAt: timestamp,
  );
}
