import 'track.dart';

/// Mirrors web/src/lib/api/history.ts HistoryEvent. Server emits
/// `{events, has_more}` rather than the standard `Page<T>` envelope —
/// history is timestamp-keyed so total isn't meaningful, only "more
/// pages exist below."
class HistoryEvent {
  const HistoryEvent({
    required this.id,
    required this.playedAt,
    required this.track,
  });

  final String id;
  /// RFC3339 timestamp; UI formats relative ("3h ago" / "Tue 14:32" /
  /// "May 1, 2025") via formatRelative helper.
  final String playedAt;
  final TrackRef track;

  factory HistoryEvent.fromJson(Map<String, dynamic> j) => HistoryEvent(
        id: j['id'] as String? ?? '',
        playedAt: j['played_at'] as String? ?? '',
        track: TrackRef.fromJson(
          (j['track'] as Map?)?.cast<String, dynamic>() ?? const {},
        ),
      );
}

class HistoryPage {
  const HistoryPage({required this.events, required this.hasMore});

  final List<HistoryEvent> events;
  final bool hasMore;

  factory HistoryPage.fromJson(Map<String, dynamic> j) {
    final raw = (j['events'] as List?) ?? const [];
    return HistoryPage(
      events: raw
          .map((e) => HistoryEvent.fromJson((e as Map).cast<String, dynamic>()))
          .toList(growable: false),
      hasMore: j['has_more'] as bool? ?? false,
    );
  }
}
