use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// Stable identity of a project asset file (mesh, texture, material,
/// prefab, scene, or audio). Minted once when the asset is first imported,
/// stored in the asset's `.meta` sidecar, and never changed, so references
/// survive renames and moves. Distinct from
/// [`AssetUuid`](super::asset_uuid::AssetUuid), which identifies an entity
/// within a single scene.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AssetGuid(uuid::Uuid);

impl AssetGuid {
    /// Mints a fresh, random asset identity (UUIDv4).
    pub fn random() -> Self {
        Self(uuid::Uuid::new_v4())
    }

    pub fn from_uuid(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }

    pub fn to_uuid(&self) -> uuid::Uuid {
        self.0
    }

    pub fn as_bytes(&self) -> &[u8; 16] {
        self.0.as_bytes()
    }
}

impl fmt::Debug for AssetGuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AssetGuid({})", self.0)
    }
}

impl fmt::Display for AssetGuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for AssetGuid {
    type Err = uuid::Error;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Ok(Self(uuid::Uuid::parse_str(value)?))
    }
}

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

    #[test]
    fn round_trips_through_string() {
        let guid = AssetGuid::random();
        let parsed: AssetGuid = guid.to_string().parse().expect("parse");
        assert_eq!(guid, parsed);
    }

    #[test]
    fn serde_round_trip() {
        let guid = AssetGuid::random();
        let json = serde_json::to_string(&guid).expect("encode");
        let decoded: AssetGuid = serde_json::from_str(&json).expect("decode");
        assert_eq!(guid, decoded);
    }
}
