onwardz 0.1.0

Server-side SDK for managing Onwardz rooms (create rooms, issue join tokens, manage settings).
Documentation
//! Request options and response types for the Onwardz server API.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Options for [`OnwardzClient::create_room`](crate::OnwardzClient::create_room).
///
/// Absent fields fall back to the server defaults (no cap, no expiry).
#[derive(Debug, Default, Clone, Serialize)]
pub struct CreateRoomOptions {
    /// Cap on simultaneous participants (2–1000).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_participants: Option<i32>,
    /// ISO 8601 expiry timestamp; absent means the room never expires.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

/// Options for
/// [`OnwardzClient::configure_room`](crate::OnwardzClient::configure_room).
///
/// Each field is an `Option<Option<T>>` to mirror the server's update
/// semantics precisely:
/// - `None` (default) — leave the field unchanged.
/// - `Some(None)` — clear the field (sent as JSON `null`).
/// - `Some(Some(v))` — set the field to `v`.
///
/// Use the builder-style setters for ergonomics, e.g.
/// `ConfigureRoomOptions::new().max_participants(20).clear_expiry()`.
#[derive(Debug, Default, Clone, Serialize)]
pub struct ConfigureRoomOptions {
    /// Participant cap. `None` = unchanged, `Some(None)` = clear, `Some(Some(n))` = set.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "double_option::serialize"
    )]
    pub max_participants: Option<Option<i32>>,
    /// ISO 8601 expiry. `None` = unchanged, `Some(None)` = clear, `Some(Some(ts))` = set.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "double_option::serialize"
    )]
    pub expires_at: Option<Option<String>>,
    /// Arbitrary JSON metadata. `None` = unchanged, `Some(None)` = clear, `Some(Some(v))` = set.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "double_option::serialize"
    )]
    pub metadata: Option<Option<Value>>,
    /// Origin allow-list. `None` = unchanged, `Some(None)` = clear, `Some(Some(v))` = set.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "double_option::serialize"
    )]
    pub allowed_origins: Option<Option<Vec<String>>>,
    /// Room theme override. `None` = unchanged, `Some(None)` = clear, `Some(Some(t))` = set.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        serialize_with = "double_option::serialize"
    )]
    pub theme: Option<Option<Theme>>,
}

impl ConfigureRoomOptions {
    /// A no-op configuration; chain setters to build it up.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the participant cap.
    pub fn max_participants(mut self, value: i32) -> Self {
        self.max_participants = Some(Some(value));
        self
    }
    /// Remove the participant cap.
    pub fn clear_max_participants(mut self) -> Self {
        self.max_participants = Some(None);
        self
    }
    /// Set the ISO 8601 expiry.
    pub fn expires_at(mut self, value: impl Into<String>) -> Self {
        self.expires_at = Some(Some(value.into()));
        self
    }
    /// Remove the expiry (never expires).
    pub fn clear_expiry(mut self) -> Self {
        self.expires_at = Some(None);
        self
    }
    /// Attach arbitrary JSON metadata.
    pub fn metadata(mut self, value: Value) -> Self {
        self.metadata = Some(Some(value));
        self
    }
    /// Set the origin allow-list for browser clients.
    pub fn allowed_origins(mut self, value: Vec<String>) -> Self {
        self.allowed_origins = Some(Some(value));
        self
    }
    /// Set the room's theme (overrides the account default).
    pub fn theme(mut self, value: Theme) -> Self {
        self.theme = Some(Some(value));
        self
    }
    /// Clear the room's theme (falls back to the account default).
    pub fn clear_theme(mut self) -> Self {
        self.theme = Some(None);
        self
    }
}

/// Curated look-and-feel for the embedded `<onwardz-room>` element. All fields
/// are optional; anything unset falls back to the built-in defaults. Mirrors
/// the 5 keys validated server-side and mapped in `@onwardz/js`.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Theme {
    /// Primary/brand color (e.g. `#5E6AD2`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accent: Option<String>,
    /// Call-surface background base.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surface: Option<String>,
    /// Primary text color on the call surface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Corner roundness preset: `none`, `sm`, `md`, or `lg`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub radius: Option<String>,
    /// Primary font family name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font: Option<String>,
}

/// Returned by [`OnwardzClient::create_room`](crate::OnwardzClient::create_room).
#[derive(Debug, Clone, Deserialize)]
pub struct CreateRoomResponse {
    /// The new room's ID.
    pub room_id: String,
    /// The creator's peer ID.
    pub peer_id: String,
    /// Whether the "Powered by Onwardz" badge is shown (free tier).
    pub show_branding: bool,
    /// The room's effective theme (its account default, if any).
    #[serde(default)]
    pub theme: Option<Theme>,
}

/// A room owned by the account, as returned by
/// [`OnwardzClient::list_rooms`](crate::OnwardzClient::list_rooms).
#[derive(Debug, Clone, Deserialize)]
pub struct Room {
    /// The room ID.
    pub id: String,
    /// Participant cap, if set.
    #[serde(default)]
    pub max_participants: Option<i32>,
    /// ISO 8601 expiry, if set.
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Arbitrary JSON metadata attached to the room.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Origin allow-list for browser clients.
    #[serde(default)]
    pub allowed_origins: Option<Vec<String>>,
    /// ISO 8601 creation timestamp.
    pub created_at: String,
    /// The room's per-room theme override, if set.
    #[serde(default)]
    pub theme: Option<Theme>,
}

/// Returned by [`OnwardzClient::issue_token`](crate::OnwardzClient::issue_token).
#[derive(Debug, Clone, Deserialize)]
pub struct IssueTokenResponse {
    /// The signed JWT a browser client passes to `OnwardzRoom`.
    pub token: String,
    /// ISO 8601 expiry of the token, if returned by the server.
    #[serde(default)]
    pub expires_at: Option<String>,
}

/// Internal wrapper for the `rooms.list` result (`{ "rooms": [...] }`).
#[derive(Debug, Deserialize)]
pub(crate) struct ListRoomsResponse {
    pub rooms: Vec<Room>,
}

/// Serialize `Option<Option<T>>` such that `Some(None)` emits an explicit JSON
/// `null` and `Some(Some(v))` emits `v`. The outer `None` case is elided by
/// `skip_serializing_if = "Option::is_none"` on the field, so it never reaches
/// here — but handle it as `null` defensively.
mod double_option {
    use serde::{Serialize, Serializer};

    pub fn serialize<T, S>(value: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        match value {
            Some(inner) => inner.serialize(serializer),
            None => serializer.serialize_none(),
        }
    }
}

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

    #[test]
    fn configure_options_omit_vs_clear_vs_set() {
        // Default: no fields serialized at all (all left unchanged server-side).
        assert_eq!(
            serde_json::to_value(ConfigureRoomOptions::new()).unwrap(),
            json!({})
        );

        // Clear vs set are distinguishable: explicit null vs value.
        let opts = ConfigureRoomOptions::new()
            .max_participants(20)
            .clear_expiry();
        assert_eq!(
            serde_json::to_value(opts).unwrap(),
            json!({ "max_participants": 20, "expires_at": null })
        );

        // A set theme serializes only its populated keys.
        let opts = ConfigureRoomOptions::new().theme(Theme {
            accent: Some("#5E6AD2".into()),
            ..Default::default()
        });
        assert_eq!(
            serde_json::to_value(opts).unwrap(),
            json!({ "theme": { "accent": "#5E6AD2" } })
        );

        // Clearing the theme sends explicit null.
        assert_eq!(
            serde_json::to_value(ConfigureRoomOptions::new().clear_theme()).unwrap(),
            json!({ "theme": null })
        );
    }

    #[test]
    fn create_options_skip_absent_fields() {
        assert_eq!(
            serde_json::to_value(CreateRoomOptions::default()).unwrap(),
            json!({})
        );
        let opts = CreateRoomOptions {
            max_participants: Some(5),
            expires_at: None,
        };
        assert_eq!(
            serde_json::to_value(opts).unwrap(),
            json!({ "max_participants": 5 })
        );
    }

    #[test]
    fn room_deserializes_with_optional_fields() {
        let room: Room = serde_json::from_value(json!({
            "id": "room_abc",
            "created_at": "2026-01-01T00:00:00Z",
            "theme": { "accent": "#000000" }
        }))
        .unwrap();
        assert_eq!(room.id, "room_abc");
        assert_eq!(room.max_participants, None);
        assert_eq!(room.theme.unwrap().accent.as_deref(), Some("#000000"));
    }
}