import 'package:freezed_annotation/freezed_annotation.dart';

import 'auth.dart';
import 'danmaku.dart';
import 'script_widget.dart';
import 'server.dart';

part 'backup.freezed.dart';
part 'backup.g.dart';


@freezed
abstract class BackupBundle with _$BackupBundle {
  const factory BackupBundle({
    required int version,
    required String exportedAt,
    required List<EmbyServer> servers,
    required List<SessionData> sessions,
    @JsonKey(fromJson: _danmakuSourcesFromJson, toJson: _danmakuSourcesToJson)
    @Default(<DanmakuSource>[])
    List<DanmakuSource> danmakuSources,
    @Default(<InstalledScriptWidget>[])
    List<InstalledScriptWidget> scriptWidgets,
    @Default(<ScriptWidgetSubscription>[])
    List<ScriptWidgetSubscription> scriptWidgetSubscriptions,
  }) = _BackupBundle;

  factory BackupBundle.fromJson(Map<String, dynamic> json) =>
      _$BackupBundleFromJson(json);
}

List<DanmakuSource> _danmakuSourcesFromJson(Object? raw) {
  if (raw is! List) return const [];
  final out = <DanmakuSource>[];
  for (final item in raw) {
    if (item is Map<String, dynamic>) {
      final source = DanmakuSource.fromJson(item);
      if (source.url.isNotEmpty) out.add(source);
    }
  }
  return out;
}

List<Map<String, dynamic>> _danmakuSourcesToJson(List<DanmakuSource> sources) {
  return [
    for (final s in sources)
      if (s.url.trim().isNotEmpty) {'url': s.url.trim(), 'name': s.name},
  ];
}
