//! Compile-time markers that encode whether a packet carries binary attachments
//! and/or expects an acknowledgement.
//!
//! Socket.IO packets vary along two independent axes:
//!
//! | Axis | "Yes" marker | "No" marker | Policy trait |
//! |------|-------------|-------------|--------------|
//! | Binary attachments | [`HasBinary`] | [`NoBinary`] | [`BinaryMarker`] |
//! | Acknowledgement | [`HasAck`] | [`NoAck`] | [`AckMarker`] |
//!
//! Generic types like [`Event`](crate::event::Event) and
//! [`Ack`](crate::ack::Ack) are parameterised over these markers
//! so the compiler catches misuse (e.g. sending binary data where none is
//! expected) at build time rather than at runtime.

use crate::ack::AckType;
use crate::error::{AckIdError, AttachmentsError};
use bytes::Bytes;
use std::fmt::DebugMap;
use std::marker::PhantomData;

/// Determines how acknowledgement IDs are handled at the type level.
pub trait AckMarker {
    /// [`AckId`] when an ack is expected, `()` when not.
    type Id: Sized;

    /// Validates and extracts an ack ID from the wire-level `Option`.
    ///
    /// # Errors
    ///
    /// Returns an error if the presence of an ID does not match the policy.
    fn parse(id: Option<u64>) -> Result<Self::Id, AckIdError>;

    /// Inserts the ack ID into `map` for debug output.
    fn format(id: &Self::Id, map: &mut DebugMap<'_, '_>);
}

/// Marker: this packet does **not** expect an acknowledgement.
#[derive(Debug)]
pub struct NoAck;

impl AckMarker for NoAck {
    type Id = ();

    fn parse(id: Option<u64>) -> Result<Self::Id, AckIdError> {
        match id {
            Some(_) => Err(AckIdError::Unexpected),
            None => Ok(()),
        }
    }

    fn format(_id: &Self::Id, _map: &mut DebugMap<'_, '_>) {}
}

/// Marker: this packet expects an acknowledgement of type `A`.
#[derive(Debug)]
pub struct HasAck<A>(PhantomData<A>);

impl<A> AckMarker for HasAck<A>
where
    A: AckType,
{
    type Id = AckId<A>;

    fn parse(id: Option<u64>) -> Result<Self::Id, AckIdError> {
        id.map(AckId::new).ok_or(AckIdError::Missing)
    }

    fn format(id: &Self::Id, map: &mut DebugMap<'_, '_>) {
        map.entry(&"id", &id.0);
    }
}

/// A raw ack ID wrapped with the expected ack payload type `A`.
///
/// This ensures that when you send an ack via [`SocketSender::acknowledge`](crate::client::SocketSender::acknowledge),
/// the response type matches what the sender originally requested.
#[must_use = "AckId must be used to acknowledge the event"]
pub struct AckId<A>(u64, PhantomData<A>);

impl<A> std::fmt::Debug for AckId<A> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AckId").field(&self.0).finish()
    }
}

impl<A> AckId<A> {
    fn new(id: u64) -> Self {
        Self(id, PhantomData)
    }

    /// Consumes the wrapper and returns the raw wire-level `u64` ID.
    #[must_use]
    pub fn get(self) -> u64 {
        self.0
    }
}

/// Determines how binary attachments are handled at the type level.
pub trait BinaryMarker {
    /// `Vec<Bytes>` when binary is present, `()` when absent.
    type Attachments: Sized;

    /// Validates and extracts attachments from the wire-level `Option`.
    ///
    /// # Errors
    ///
    /// Returns an error if attachment presence does not match the policy.
    fn parse(attachment: Option<Vec<Bytes>>) -> Result<Self::Attachments, AttachmentsError>;

    /// Converts typed attachments back into the wire-level `Option`.
    fn get(attachments: Self::Attachments) -> Option<Vec<Bytes>>;

    /// Inserts the attachment count into `map` for debug output.
    fn format(attachments: &Self::Attachments, map: &mut DebugMap<'_, '_>);
}

/// Marker: this packet carries binary attachments.
#[derive(Debug)]
pub struct HasBinary;

/// Marker: this packet has no binary attachments.
#[derive(Debug)]
pub struct NoBinary;

impl BinaryMarker for NoBinary {
    type Attachments = ();

    fn parse(attachment: Option<Vec<Bytes>>) -> Result<Self::Attachments, AttachmentsError> {
        match attachment {
            Some(_) => Err(AttachmentsError::Unexpected),
            None => Ok(()),
        }
    }

    fn get(_attachments: Self::Attachments) -> Option<Vec<Bytes>> {
        None
    }

    fn format(_attachments: &Self::Attachments, _map: &mut DebugMap<'_, '_>) {}
}

impl BinaryMarker for HasBinary {
    type Attachments = Vec<Bytes>;

    fn parse(attachment: Option<Vec<Bytes>>) -> Result<Self::Attachments, AttachmentsError> {
        attachment.ok_or(AttachmentsError::Missing)
    }

    fn get(attachments: Self::Attachments) -> Option<Vec<Bytes>> {
        Some(attachments)
    }

    fn format(attachments: &Self::Attachments, map: &mut DebugMap<'_, '_>) {
        map.entry(&"count", &attachments.len());
    }
}

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

    fn fmt_markers<F: Fn(&mut DebugMap)>(f: F) -> String {
        struct W<F>(F);
        impl<F: Fn(&mut DebugMap)> std::fmt::Debug for W<F> {
            fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let mut map = fmt.debug_map();
                (self.0)(&mut map);
                map.finish()
            }
        }
        format!("{:?}", W(f))
    }

    #[test]
    fn no_ack_format_is_empty() {
        assert_eq!(fmt_markers(|m| NoAck::format(&(), m)), "{}");
    }

    #[test]
    fn has_ack_format_inserts_id() {
        let id = <HasAck<()>>::parse(Some(42)).unwrap();
        assert_eq!(
            fmt_markers(|m| HasAck::<()>::format(&id, m)),
            r#"{"id": 42}"#
        );
    }

    #[test]
    fn no_binary_format_is_empty() {
        assert_eq!(fmt_markers(|m| NoBinary::format(&(), m)), "{}");
    }

    #[test]
    fn has_binary_format_inserts_count() {
        let attachments = vec![Bytes::from_static(b"x"), Bytes::from_static(b"y")];
        assert_eq!(
            fmt_markers(|m| HasBinary::format(&attachments, m)),
            r#"{"count": 2}"#
        );
    }

    #[test]
    fn no_binary_parse_none_succeeds() {
        NoBinary::parse(None).unwrap();
    }

    #[test]
    fn no_binary_parse_some_fails() {
        let attachments = Some(vec![Bytes::from_static(b"data")]);
        assert!(NoBinary::parse(attachments).is_err());
    }

    #[test]
    fn no_binary_get_returns_none() {
        assert!(NoBinary::get(()).is_none());
    }

    #[test]
    fn has_binary_parse_some_succeeds() {
        let input = vec![Bytes::from_static(b"a"), Bytes::from_static(b"b")];
        let parsed = HasBinary::parse(Some(input.clone())).unwrap();
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0], input[0]);
    }

    #[test]
    fn has_binary_parse_none_fails() {
        HasBinary::parse(None).unwrap_err();
    }

    #[test]
    fn has_binary_get_returns_some() {
        let input = vec![Bytes::from_static(b"x")];
        let result = HasBinary::get(input.clone());
        assert_eq!(result.unwrap(), input);
    }

    #[test]
    fn no_ack_parse_none_succeeds() {
        NoAck::parse(None).unwrap();
    }

    #[test]
    fn no_ack_parse_some_fails() {
        assert!(NoAck::parse(Some(42)).is_err());
    }

    #[test]
    fn has_ack_parse_some_succeeds() {
        let id = <HasAck<()>>::parse(Some(7)).unwrap();
        assert_eq!(id.get(), 7);
    }

    #[test]
    fn has_ack_parse_none_fails() {
        <HasAck<()>>::parse(None).unwrap_err();
    }
}
