// Mirrors internal/api/types.go TrackRef and web/src/lib/api/types.ts.
//
// Server uses `duration_sec` (NOT duration_ms). `track_number` and
// `disc_number` are omitempty server-side so they're nullable here.
// `stream_url` points at /api/tracks/{id}/stream.
class TrackRef {
  const TrackRef({
    required this.id,
    required this.title,
    required this.albumId,
    required this.artistId,
    this.albumTitle = '',
    this.artistName = '',
    this.trackNumber,
    this.discNumber,
    this.durationSec = 0,
    this.streamUrl = '',
  });

  final String id;
  final String title;
  final String albumId;
  final String albumTitle;
  final String artistId;
  final String artistName;
  final int? trackNumber;
  final int? discNumber;
  final int durationSec;
  final String streamUrl;

  factory TrackRef.fromJson(Map<String, dynamic> j) => TrackRef(
        id: j['id'] as String,
        title: j['title'] as String,
        albumId: j['album_id'] as String,
        albumTitle: j['album_title'] as String? ?? '',
        artistId: j['artist_id'] as String,
        artistName: j['artist_name'] as String? ?? '',
        trackNumber: (j['track_number'] as num?)?.toInt(),
        discNumber: (j['disc_number'] as num?)?.toInt(),
        durationSec: (j['duration_sec'] as num?)?.toInt() ?? 0,
        streamUrl: j['stream_url'] as String? ?? '',
      );

  /// Round-trips through [TrackRef.fromJson] (same server snake_case
  /// keys). Used to persist the playback queue for resume-on-launch.
  Map<String, dynamic> toJson() => {
        'id': id,
        'title': title,
        'album_id': albumId,
        'album_title': albumTitle,
        'artist_id': artistId,
        'artist_name': artistName,
        if (trackNumber != null) 'track_number': trackNumber,
        if (discNumber != null) 'disc_number': discNumber,
        'duration_sec': durationSec,
        'stream_url': streamUrl,
      };
}
