import 'trakt_ids.dart';


enum TraktMediaKind { movie, episode }


class TraktScrobbleTarget {
  final TraktMediaKind kind;

  final String title;
  final int? year;
  final TraktIds ids;

  final int? season;
  final int? number;
  final TraktIds episodeIds;

  const TraktScrobbleTarget._({
    required this.kind,
    required this.title,
    required this.year,
    required this.ids,
    this.season,
    this.number,
    this.episodeIds = const TraktIds(),
  });

  factory TraktScrobbleTarget.movie({
    required String title,
    required int? year,
    required TraktIds ids,
  }) {
    return TraktScrobbleTarget._(
      kind: TraktMediaKind.movie,
      title: title,
      year: year,
      ids: ids,
    );
  }

  factory TraktScrobbleTarget.episode({
    required String showTitle,
    required int? showYear,
    required TraktIds showIds,
    required int? season,
    required int? number,
    required TraktIds episodeIds,
  }) {
    return TraktScrobbleTarget._(
      kind: TraktMediaKind.episode,
      title: showTitle,
      year: showYear,
      ids: showIds,
      season: season,
      number: number,
      episodeIds: episodeIds,
    );
  }


  Map<String, dynamic> toBody({
    required double progress,
    String? appVersion,
    String? appDate,
  }) {
    final body = <String, dynamic>{};

    switch (kind) {
      case TraktMediaKind.movie:
        body['movie'] = _mediaNode(title, year, ids);
      case TraktMediaKind.episode:
        body['show'] = _mediaNode(title, year, ids);
        final episode = <String, dynamic>{'season': season, 'number': number};
        final epIds = episodeIds.toJson();
        if (epIds.isNotEmpty) episode['ids'] = epIds;
        body['episode'] = episode;
    }

    body['progress'] = progress.toDouble();
    if (appVersion != null && appVersion.isNotEmpty) {
      body['app_version'] = appVersion;
    }
    if (appDate != null && appDate.isNotEmpty) body['app_date'] = appDate;
    return body;
  }

  static Map<String, dynamic> _mediaNode(
    String title,
    int? year,
    TraktIds ids,
  ) {
    final node = <String, dynamic>{'title': title};
    if (year != null && year > 0) node['year'] = year;
    node['ids'] = ids.toJson();
    return node;
  }
}
