import 'trakt_ids.dart';


class TraktPlaybackEntry {

  final double progress;
  final DateTime? pausedAt;


  final String type;

  final String? movieTitle;
  final int? movieYear;
  final TraktIds? movieIds;

  final String? showTitle;
  final int? showYear;
  final TraktIds? showIds;

  final int? episodeSeason;
  final int? episodeNumber;
  final String? episodeTitle;
  final TraktIds? episodeIds;

  const TraktPlaybackEntry({
    required this.progress,
    required this.type,
    this.pausedAt,
    this.movieTitle,
    this.movieYear,
    this.movieIds,
    this.showTitle,
    this.showYear,
    this.showIds,
    this.episodeSeason,
    this.episodeNumber,
    this.episodeTitle,
    this.episodeIds,
  });

  static TraktPlaybackEntry? fromJson(Map<String, dynamic> json) {
    final movie = json['movie'];
    final show = json['show'];
    final episode = json['episode'];
    final hasMovie = movie is Map<String, dynamic>;
    final hasShow = show is Map<String, dynamic>;
    if (!hasMovie && !hasShow) return null;

    final rawType = json['type'] as String? ?? '';
    return TraktPlaybackEntry(
      progress: (json['progress'] as num?)?.toDouble() ?? 0,
      pausedAt: _parseDate(json['paused_at']),
      type: rawType.isNotEmpty ? rawType : (hasMovie ? 'movie' : 'episode'),
      movieTitle: hasMovie ? movie['title'] as String? : null,
      movieYear: hasMovie ? (movie['year'] as num?)?.toInt() : null,
      movieIds: hasMovie ? TraktIds.fromJson(movie['ids']) : null,
      showTitle: hasShow ? show['title'] as String? : null,
      showYear: hasShow ? (show['year'] as num?)?.toInt() : null,
      showIds: hasShow ? TraktIds.fromJson(show['ids']) : null,
      episodeSeason: episode is Map<String, dynamic>
          ? (episode['season'] as num?)?.toInt()
          : null,
      episodeNumber: episode is Map<String, dynamic>
          ? (episode['number'] as num?)?.toInt()
          : null,
      episodeTitle: episode is Map<String, dynamic>
          ? episode['title'] as String?
          : null,
      episodeIds: episode is Map<String, dynamic>
          ? TraktIds.fromJson(episode['ids'])
          : null,
    );
  }
}

DateTime? _parseDate(Object? raw) {
  if (raw is! String || raw.isEmpty) return null;
  return DateTime.tryParse(raw);
}
