use serde::{Deserialize, Serialize};

/// Error types for repository operations
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum RepoError {
    Network { message: String },
    Authentication { message: String },
    NotFound { message: String },
    Server { message: String },
    Database { message: String },
    Offline,
}

impl std::fmt::Display for RepoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RepoError::Network { message } => write!(f, "Network error: {}", message),
            RepoError::Authentication { message } => write!(f, "Authentication error: {}", message),
            RepoError::NotFound { message } => write!(f, "Not found: {}", message),
            RepoError::Server { message } => write!(f, "Server error: {}", message),
            RepoError::Database { message } => write!(f, "Database error: {}", message),
            RepoError::Offline => write!(f, "Offline - no server connection"),
        }
    }
}

impl std::error::Error for RepoError {}

/// Library (media collection)
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Library {
    pub id: String,
    pub name: String,
    pub collection_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_tag: Option<String>,
}

/// User-specific data for an item (playback state, favorites, etc.)
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserData {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub playback_position_ticks: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_played: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_favorite: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub play_count: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_played_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub playback_context_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub playback_context_id: Option<String>,
}

/// Artist item with ID and name (for clickable artist links)
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ArtistItem {
    #[serde(alias = "Id")]
    pub id: String,
    #[serde(alias = "Name")]
    pub name: String,
}

/// Person (cast/crew member) - for movies, series, and episodes
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Person {
    /// Deserializes from API's "Id" field (PascalCase), serializes as "id" (camelCase to frontend)
    #[serde(alias = "Id")]
    #[serde(default)]
    pub id: String,
    /// Deserializes from API's "Name" field (PascalCase), serializes as "name" (camelCase to frontend)
    #[serde(alias = "Name")]
    #[serde(default)]
    pub name: String,
    /// Person type from Jellyfin API (Actor, Director, Writer, etc.)
    /// Deserializes from API's "Type" field (PascalCase), serializes as "type" (camelCase to frontend)
    #[serde(rename = "type")]
    #[serde(alias = "Type")]
    #[serde(default)]
    pub person_type: String,
    /// Deserializes from API's "Role" field (PascalCase), serializes as "role" (camelCase to frontend)
    #[serde(alias = "Role")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Deserializes from API's "PrimaryImageTag" field (PascalCase), serializes as "primaryImageTag" (camelCase to frontend)
    #[serde(alias = "PrimaryImageTag")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary_image_tag: Option<String>,
}

/// Media item
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaItem {
    pub id: String,
    pub name: String,
    #[serde(rename = "type")]
    pub item_type: String,
    /// Whether this item is a folder/container (vs a playable leaf). Used to
    /// decide whether a channel item drills into a list or plays directly.
    #[serde(default)]
    pub is_folder: bool,
    pub server_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub library_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub overview: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub genres: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub production_year: Option<i32>,
    /// ISO-8601 release/air date (Jellyfin `PremiereDate`). Used to sort
    /// podcast episodes by release date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub premiere_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub community_rating: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub official_rating: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "runTimeTicks")]
    pub runtime_ticks: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary_image_tag: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backdrop_image_tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_backdrop_image_tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub album_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub album_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub album_artist: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artists: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artist_items: Option<Vec<ArtistItem>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index_number: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_index_number: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub series_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub series_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub season_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub season_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_data: Option<UserData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_streams: Option<Vec<MediaStream>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_sources: Option<Vec<MediaSource>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub people: Option<Vec<Person>>,
}

/// Media stream information (audio, video, subtitle tracks)
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaStream {
    #[serde(rename = "type")]
    pub stream_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub codec: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_title: Option<String>,
    pub index: i32,
    pub is_default: bool,
    pub is_forced: bool,
}

/// Media source information
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaSource {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bitrate: Option<i32>,
    pub supports_direct_play: bool,
    pub supports_direct_stream: bool,
    pub supports_transcoding: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direct_stream_url: Option<String>,
}

/// Search result with pagination
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchResult {
    pub items: Vec<MediaItem>,
    pub total_record_count: usize,
}

/// On-disk usage of downloaded content, for the Downloads surface.
///
/// `sizes` maps an item id (leaf *or* container) to its bytes on disk: a leaf's
/// own file size, a container's summed downloaded descendants. `device_total_bytes`
/// and `item_count` are the headline figures for the Downloaded surface top bar.
///
/// TRACES: UR-056 | DR-085
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadDiskUsage {
    /// item id → bytes on disk (leaf's own size, or a container's subtotal).
    pub sizes: std::collections::HashMap<String, i64>,
    /// Container id → true when it is only *partially* downloaded (has cached
    /// children that are not downloaded). Absent/false ⇒ fully downloaded. Lets
    /// the Downloaded surface badge partial vs. full containers.
    pub partial_containers: std::collections::HashMap<String, bool>,
    /// Sum of all downloaded leaf sizes — the device total.
    pub device_total_bytes: i64,
    /// Number of downloaded leaf items (not containers).
    pub item_count: u32,
}

/// Options for querying items
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GetItemsOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_index: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_order: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_item_types: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recursive: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub genres: Option<Vec<String>>,
}

/// Options for search queries
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SearchOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_item_types: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_term: Option<String>,
}

/// Playback information
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaybackInfo {
    pub media_source_id: String,
    pub play_session_id: String,
    pub stream_url: String,
    pub direct_play: bool,
    pub needs_transcoding: bool,
}

/// Live stream information returned from opening a Live TV / channel stream.
///
/// Unlike on-demand video, a live channel must be "opened" before it can be
/// streamed; the server returns a transcoding URL (already absolute) plus a
/// `live_stream_id` that can later be used to close the stream.
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiveStreamInfo {
    pub stream_url: String,
    pub play_session_id: Option<String>,
    pub live_stream_id: Option<String>,
    pub media_source_id: Option<String>,
}

/// Genre
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Genre {
    pub id: String,
    pub name: String,
    /// Number of albums tagged with this genre, when the backend can supply it
    /// (online only). Lets the frontend rank/pick genres without probing each
    /// one. `None` when unknown (e.g. offline).
    pub album_count: Option<u32>,
}

/// Image type
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
pub enum ImageType {
    Primary,
    Backdrop,
    Banner,
    Thumb,
    Logo,
}

impl ImageType {
    pub fn as_str(&self) -> &str {
        match self {
            ImageType::Primary => "Primary",
            ImageType::Backdrop => "Backdrop",
            ImageType::Banner => "Banner",
            ImageType::Thumb => "Thumb",
            ImageType::Logo => "Logo",
        }
    }
}

/// Image options
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_height: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
}

/// Trait for checking if data has meaningful content
pub trait MeaningfulContent {
    fn has_content(&self) -> bool;
}

impl MeaningfulContent for Vec<Library> {
    fn has_content(&self) -> bool {
        !self.is_empty()
    }
}

impl MeaningfulContent for Vec<MediaItem> {
    fn has_content(&self) -> bool {
        !self.is_empty()
    }
}

impl MeaningfulContent for SearchResult {
    fn has_content(&self) -> bool {
        !self.items.is_empty()
    }
}

impl MeaningfulContent for MediaItem {
    fn has_content(&self) -> bool {
        true // A single item always has content if it exists
    }
}

impl MeaningfulContent for Vec<Genre> {
    fn has_content(&self) -> bool {
        !self.is_empty()
    }
}

impl MeaningfulContent for PlaybackInfo {
    fn has_content(&self) -> bool {
        !self.stream_url.is_empty()
    }
}

/// Playlist entry — wraps a MediaItem with the Jellyfin PlaylistItemId
/// needed for remove/reorder operations (distinct from the media item's ID)
///
/// @req: UR-014 - Make and edit playlists of music that sync back to Jellyfin
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaylistEntry {
    /// The playlist-scoped entry ID (Jellyfin's PlaylistItemId)
    pub playlist_item_id: String,
    /// The underlying media item
    #[serde(flatten)]
    pub item: MediaItem,
}

/// Result of creating a playlist
///
/// @req: JA-019 - Get/create/update playlists
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaylistCreatedResult {
    pub id: String,
}

impl MeaningfulContent for Vec<PlaylistEntry> {
    fn has_content(&self) -> bool {
        !self.is_empty()
    }
}

impl MeaningfulContent for PlaylistCreatedResult {
    fn has_content(&self) -> bool {
        !self.id.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_artist_item_deserialize_pascal_case() {
        // Test that ArtistItem correctly deserializes PascalCase JSON from Jellyfin API
        let json = r#"{"Id": "artist123", "Name": "Bob Dylan"}"#;
        let result: Result<ArtistItem, _> = serde_json::from_str(json);

        assert!(result.is_ok());
        let artist = result.unwrap();
        assert_eq!(artist.id, "artist123");
        assert_eq!(artist.name, "Bob Dylan");
    }

    #[test]
    fn test_artist_item_deserialize_array() {
        // Test deserializing array of ArtistItems (common in API responses)
        let json = r#"[
            {"Id": "artist1", "Name": "Bob Dylan"},
            {"Id": "artist2", "Name": "Johnny Cash"}
        ]"#;
        let result: Result<Vec<ArtistItem>, _> = serde_json::from_str(json);

        assert!(result.is_ok());
        let artists = result.unwrap();
        assert_eq!(artists.len(), 2);
        assert_eq!(artists[0].id, "artist1");
        assert_eq!(artists[0].name, "Bob Dylan");
        assert_eq!(artists[1].id, "artist2");
        assert_eq!(artists[1].name, "Johnny Cash");
    }

    #[test]
    fn test_artist_item_serialize() {
        // ArtistItem serializes to camelCase for the frontend; it still accepts
        // Jellyfin's PascalCase on deserialize via #[serde(alias = ...)].
        let artist = ArtistItem {
            id: "test-id".to_string(),
            name: "Test Artist".to_string(),
        };

        let json = serde_json::to_string(&artist).expect("Failed to serialize");
        assert!(json.contains(r#""id":"test-id""#));
        assert!(json.contains(r#""name":"Test Artist""#));

        let from_pascal: ArtistItem =
            serde_json::from_str(r#"{"Id":"x","Name":"Y"}"#).expect("Failed to deserialize");
        assert_eq!(from_pascal.id, "x");
        assert_eq!(from_pascal.name, "Y");
    }

    #[test]
    fn test_media_item_with_primary_image_tag() {
        // Test that MediaItem correctly handles primary_image_tag
        let json = r#"{
            "id": "item123",
            "name": "Test Item",
            "type": "MusicAlbum",
            "serverId": "server1",
            "primaryImageTag": "tag123"
        }"#;

        let result: Result<MediaItem, _> = serde_json::from_str(json);
        assert!(result.is_ok());

        let item = result.unwrap();
        assert_eq!(item.id, "item123");
        assert_eq!(item.name, "Test Item");
        assert_eq!(item.primary_image_tag, Some("tag123".to_string()));
    }

    #[test]
    fn test_media_item_with_artists() {
        // Test MediaItem with artists array
        let json = r#"{
            "id": "track1",
            "name": "Test Track",
            "type": "Audio",
            "serverId": "server1",
            "artists": ["Artist 1", "Artist 2"]
        }"#;

        let result: Result<MediaItem, _> = serde_json::from_str(json);
        assert!(result.is_ok());

        let item = result.unwrap();
        let artists = item.artists.expect("Expected artists");
        assert_eq!(artists.len(), 2);
        assert_eq!(artists[0], "Artist 1");
        assert_eq!(artists[1], "Artist 2");
    }

    #[test]
    fn test_search_result_meaningful_content() {
        // Test MeaningfulContent trait for SearchResult
        let empty_result = SearchResult {
            items: vec![],
            total_record_count: 0,
        };
        assert!(!empty_result.has_content());

        let non_empty_result = SearchResult {
            items: vec![MediaItem {
                id: "1".to_string(),
                name: "Test".to_string(),
                item_type: "Audio".to_string(),
                is_folder: false,
                server_id: "server1".to_string(),
                parent_id: None,
                library_id: None,
                overview: None,
                genres: None,
                production_year: None,
                premiere_date: None,
                community_rating: None,
                official_rating: None,
                runtime_ticks: None,
                primary_image_tag: None,
                backdrop_image_tags: None,
                parent_backdrop_image_tags: None,
                album_id: None,
                album_name: None,
                album_artist: None,
                artists: None,
                artist_items: None,
                index_number: None,
                parent_index_number: None,
                series_id: None,
                series_name: None,
                season_id: None,
                season_name: None,
                user_data: None,
                media_streams: None,
                media_sources: None,
                people: None,
            }],
            total_record_count: 1,
        };
        assert!(non_empty_result.has_content());
    }

    #[test]
    fn test_person_deserialize_complete() {
        // Test that Person deserializes correctly with all fields (PascalCase from Jellyfin API)
        let json = r#"{
            "Id": "person123",
            "Name": "Tom Hanks",
            "Type": "Actor",
            "Role": "Lead Actor",
            "PrimaryImageTag": "tag456"
        }"#;

        let result: Result<Person, _> = serde_json::from_str(json);
        assert!(result.is_ok(), "Failed to deserialize: {:?}", result.err());

        let person = result.unwrap();
        assert_eq!(person.id, "person123");
        assert_eq!(person.name, "Tom Hanks");
        assert_eq!(person.person_type, "Actor");
        assert_eq!(person.role, Some("Lead Actor".to_string()));
        assert_eq!(person.primary_image_tag, Some("tag456".to_string()));

        // Verify serialization uses camelCase for frontend
        let serialized = serde_json::to_string(&person).expect("Failed to serialize");
        assert!(
            serialized.contains(r#""type":"Actor""#),
            "Serialized form should use 'type' not 'Type'"
        );
        assert!(serialized.contains(r#""id":"person123""#));
        assert!(serialized.contains(r#""primaryImageTag":"tag456""#));
    }

    #[test]
    fn test_person_deserialize_minimal() {
        // Test that Person deserializes with missing optional fields (uses defaults)
        let json = r#"{
            "Id": "person456",
            "Name": "Meryl Streep",
            "Type": "Actress"
        }"#;

        let result: Result<Person, _> = serde_json::from_str(json);
        assert!(result.is_ok());

        let person = result.unwrap();
        assert_eq!(person.id, "person456");
        assert_eq!(person.name, "Meryl Streep");
        assert_eq!(person.person_type, "Actress");
        assert_eq!(person.role, None);
        assert_eq!(person.primary_image_tag, None);
    }

    #[test]
    fn test_person_array_deserialize() {
        // Test deserializing array of Person objects (common in Jellyfin API)
        let json = r#"[
            {"Id": "actor1", "Name": "Actor One", "Type": "Actor"},
            {"Id": "director1", "Name": "Director One", "Type": "Director", "Role": "Director"}
        ]"#;

        let result: Result<Vec<Person>, _> = serde_json::from_str(json);
        assert!(result.is_ok());

        let people = result.unwrap();
        assert_eq!(people.len(), 2);
        assert_eq!(people[0].name, "Actor One");
        assert_eq!(people[1].person_type, "Director");
        assert_eq!(people[1].role, Some("Director".to_string()));
    }

    #[test]
    fn test_media_item_with_people() {
        // Test that MediaItem correctly deserializes with people array (from API in PascalCase)
        let json = r#"{
            "id": "movie1",
            "name": "Test Movie",
            "type": "Movie",
            "serverId": "server1",
            "people": [
                {"Id": "actor1", "Name": "John Doe", "Type": "Actor"},
                {"Id": "director1", "Name": "Jane Smith", "Type": "Director"}
            ]
        }"#;

        let result: Result<MediaItem, _> = serde_json::from_str(json);
        assert!(result.is_ok());

        let item = result.unwrap();
        let people = item.people.as_ref().expect("Expected people array");
        assert_eq!(people.len(), 2);
        assert_eq!(people[0].name, "John Doe");
        assert_eq!(people[0].person_type, "Actor");
        assert_eq!(people[1].person_type, "Director");

        // Verify that when serialized to frontend, it uses camelCase
        let serialized = serde_json::to_string(&item).expect("Failed to serialize");
        let re_parsed: serde_json::Value =
            serde_json::from_str(&serialized).expect("Failed to parse serialized");
        let people_array = re_parsed["people"]
            .as_array()
            .expect("people should be array");
        assert!(
            people_array[0].get("type").is_some(),
            "Serialized person should have 'type' field"
        );
        assert_eq!(people_array[0]["type"].as_str().unwrap(), "Actor");
    }

    #[test]
    fn test_playlist_entry_serialization() {
        let entry = PlaylistEntry {
            playlist_item_id: "entry-abc-123".to_string(),
            item: MediaItem {
                id: "track1".to_string(),
                name: "Test Track".to_string(),
                item_type: "Audio".to_string(),
                is_folder: false,
                server_id: "server1".to_string(),
                parent_id: None,
                library_id: None,
                overview: None,
                genres: None,
                production_year: None,
                premiere_date: None,
                community_rating: None,
                official_rating: None,
                runtime_ticks: None,
                primary_image_tag: None,
                backdrop_image_tags: None,
                parent_backdrop_image_tags: None,
                album_id: None,
                album_name: None,
                album_artist: None,
                artists: Some(vec!["Artist One".to_string()]),
                artist_items: None,
                index_number: None,
                parent_index_number: None,
                series_id: None,
                series_name: None,
                season_id: None,
                season_name: None,
                user_data: None,
                media_streams: None,
                media_sources: None,
                people: None,
            },
        };

        let json = serde_json::to_string(&entry).expect("Failed to serialize");
        // playlistItemId is camelCase
        assert!(json.contains(r#""playlistItemId":"entry-abc-123""#));
        // Flattened MediaItem fields appear at top level
        assert!(json.contains(r#""id":"track1""#));
        assert!(json.contains(r#""name":"Test Track""#));
        assert!(json.contains(r#""type":"Audio""#));
    }

    #[test]
    fn test_playlist_created_result_serialization() {
        let result = PlaylistCreatedResult {
            id: "playlist-new-123".to_string(),
        };
        let json = serde_json::to_string(&result).expect("Failed to serialize");
        assert!(json.contains(r#""id":"playlist-new-123""#));
    }

    #[test]
    fn test_playlist_entry_meaningful_content() {
        let empty: Vec<PlaylistEntry> = vec![];
        assert!(!empty.has_content());

        let non_empty = vec![PlaylistEntry {
            playlist_item_id: "e1".to_string(),
            item: MediaItem {
                id: "1".to_string(),
                name: "Track".to_string(),
                item_type: "Audio".to_string(),
                is_folder: false,
                server_id: "s1".to_string(),
                parent_id: None,
                library_id: None,
                overview: None,
                genres: None,
                production_year: None,
                premiere_date: None,
                community_rating: None,
                official_rating: None,
                runtime_ticks: None,
                primary_image_tag: None,
                backdrop_image_tags: None,
                parent_backdrop_image_tags: None,
                album_id: None,
                album_name: None,
                album_artist: None,
                artists: None,
                artist_items: None,
                index_number: None,
                parent_index_number: None,
                series_id: None,
                series_name: None,
                season_id: None,
                season_name: None,
                user_data: None,
                media_streams: None,
                media_sources: None,
                people: None,
            },
        }];
        assert!(non_empty.has_content());
    }
}
