use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;

use super::chapter::Chapter;
use super::manga::Manga;

/// Tagged union used by `GET /me/uploads` to interleave manga + chapter
/// rows chronologically. Serialised as `{ "kind": "...", ... }` so a
/// TypeScript discriminated union can pattern-match on `kind`.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UploadEntry {
    Manga {
        manga: Manga,
        /// Mirrored from `manga.created_at` for ordering convenience;
        /// the frontend reads this to display the timestamp in a
        /// kind-agnostic column.
        created_at: DateTime<Utc>,
    },
    Chapter {
        manga_id: Uuid,
        manga_title: String,
        manga_cover_image_path: Option<String>,
        chapter: Chapter,
        created_at: DateTime<Utc>,
    },
}

impl UploadEntry {
    /// Timestamp used for chronological ordering. The repo sorts on
    /// the underlying column server-side; this is here for callers
    /// that need to merge or page in Rust.
    pub fn created_at(&self) -> DateTime<Utc> {
        match self {
            UploadEntry::Manga { created_at, .. } => *created_at,
            UploadEntry::Chapter { created_at, .. } => *created_at,
        }
    }
}
