// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.atcr.hold.crew
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::CowStr;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{Did, AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
/// Crew member in a hold's embedded PDS. Grants access permissions to push blobs to the hold. Stored in the hold's embedded PDS (one record per member).

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Crew<'a> {
    ///RFC3339 timestamp of when the member was added
    pub added_at: Datetime,
    ///DID of the crew member
    #[serde(borrow)]
    pub member: Did<'a>,
    ///Specific permissions granted to this member
    #[serde(borrow)]
    pub permissions: Vec<CowStr<'a>>,
    ///Member's role in the hold
    #[serde(borrow)]
    pub role: CrewRole<'a>,
    ///Optional tier for quota limits (e.g., 'deckhand', 'bosun', 'quartermaster'). If empty, uses defaults.new_crew_tier from quotas.yaml.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tier: Option<CowStr<'a>>,
}

/// Member's role in the hold

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CrewRole<'a> {
    Owner,
    Admin,
    Write,
    Read,
    Other(CowStr<'a>),
}

impl<'a> CrewRole<'a> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Owner => "owner",
            Self::Admin => "admin",
            Self::Write => "write",
            Self::Read => "read",
            Self::Other(s) => s.as_ref(),
        }
    }
}

impl<'a> From<&'a str> for CrewRole<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "owner" => Self::Owner,
            "admin" => Self::Admin,
            "write" => Self::Write,
            "read" => Self::Read,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for CrewRole<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "owner" => Self::Owner,
            "admin" => Self::Admin,
            "write" => Self::Write,
            "read" => Self::Read,
            _ => Self::Other(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for CrewRole<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> serde::Serialize for CrewRole<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, 'a> serde::Deserialize<'de> for CrewRole<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for CrewRole<'a> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl jacquard_common::IntoStatic for CrewRole<'_> {
    type Output = CrewRole<'static>;
    fn into_static(self) -> Self::Output {
        match self {
            CrewRole::Owner => CrewRole::Owner,
            CrewRole::Admin => CrewRole::Admin,
            CrewRole::Write => CrewRole::Write,
            CrewRole::Read => CrewRole::Read,
            CrewRole::Other(v) => CrewRole::Other(v.into_static()),
        }
    }
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct CrewGetRecordOutput<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Crew<'a>,
}

impl<'a> Crew<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, CrewRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct CrewRecord;
impl XrpcResp for CrewRecord {
    const NSID: &'static str = "io.atcr.hold.crew";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = CrewGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<CrewGetRecordOutput<'_>> for Crew<'_> {
    fn from(output: CrewGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

impl Collection for Crew<'_> {
    const NSID: &'static str = "io.atcr.hold.crew";
    type Record = CrewRecord;
}

impl Collection for CrewRecord {
    const NSID: &'static str = "io.atcr.hold.crew";
    type Record = CrewRecord;
}

impl<'a> LexiconSchema for Crew<'a> {
    fn nsid() -> &'static str {
        "io.atcr.hold.crew"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_atcr_hold_crew()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.role;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("role"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.tier {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("tier"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod crew_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Permissions;
        type AddedAt;
        type Role;
        type Member;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Permissions = Unset;
        type AddedAt = Unset;
        type Role = Unset;
        type Member = Unset;
    }
    ///State transition - sets the `permissions` field to Set
    pub struct SetPermissions<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetPermissions<S> {}
    impl<S: State> State for SetPermissions<S> {
        type Permissions = Set<members::permissions>;
        type AddedAt = S::AddedAt;
        type Role = S::Role;
        type Member = S::Member;
    }
    ///State transition - sets the `added_at` field to Set
    pub struct SetAddedAt<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetAddedAt<S> {}
    impl<S: State> State for SetAddedAt<S> {
        type Permissions = S::Permissions;
        type AddedAt = Set<members::added_at>;
        type Role = S::Role;
        type Member = S::Member;
    }
    ///State transition - sets the `role` field to Set
    pub struct SetRole<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetRole<S> {}
    impl<S: State> State for SetRole<S> {
        type Permissions = S::Permissions;
        type AddedAt = S::AddedAt;
        type Role = Set<members::role>;
        type Member = S::Member;
    }
    ///State transition - sets the `member` field to Set
    pub struct SetMember<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetMember<S> {}
    impl<S: State> State for SetMember<S> {
        type Permissions = S::Permissions;
        type AddedAt = S::AddedAt;
        type Role = S::Role;
        type Member = Set<members::member>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `permissions` field
        pub struct permissions(());
        ///Marker type for the `added_at` field
        pub struct added_at(());
        ///Marker type for the `role` field
        pub struct role(());
        ///Marker type for the `member` field
        pub struct member(());
    }
}

/// Builder for constructing an instance of this type
pub struct CrewBuilder<'a, S: crew_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<Did<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<CrewRole<'a>>,
        Option<CowStr<'a>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> Crew<'a> {
    /// Create a new builder for this type
    pub fn new() -> CrewBuilder<'a, crew_state::Empty> {
        CrewBuilder::new()
    }
}

impl<'a> CrewBuilder<'a, crew_state::Empty> {
    /// Create a new builder with all fields unset
    pub fn new() -> Self {
        CrewBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None, None),
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CrewBuilder<'a, S>
where
    S: crew_state::State,
    S::AddedAt: crew_state::IsUnset,
{
    /// Set the `addedAt` field (required)
    pub fn added_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> CrewBuilder<'a, crew_state::SetAddedAt<S>> {
        self._fields.0 = Option::Some(value.into());
        CrewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CrewBuilder<'a, S>
where
    S: crew_state::State,
    S::Member: crew_state::IsUnset,
{
    /// Set the `member` field (required)
    pub fn member(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> CrewBuilder<'a, crew_state::SetMember<S>> {
        self._fields.1 = Option::Some(value.into());
        CrewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CrewBuilder<'a, S>
where
    S: crew_state::State,
    S::Permissions: crew_state::IsUnset,
{
    /// Set the `permissions` field (required)
    pub fn permissions(
        mut self,
        value: impl Into<Vec<CowStr<'a>>>,
    ) -> CrewBuilder<'a, crew_state::SetPermissions<S>> {
        self._fields.2 = Option::Some(value.into());
        CrewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> CrewBuilder<'a, S>
where
    S: crew_state::State,
    S::Role: crew_state::IsUnset,
{
    /// Set the `role` field (required)
    pub fn role(
        mut self,
        value: impl Into<CrewRole<'a>>,
    ) -> CrewBuilder<'a, crew_state::SetRole<S>> {
        self._fields.3 = Option::Some(value.into());
        CrewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: crew_state::State> CrewBuilder<'a, S> {
    /// Set the `tier` field (optional)
    pub fn tier(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `tier` field to an Option value (optional)
    pub fn maybe_tier(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> CrewBuilder<'a, S>
where
    S: crew_state::State,
    S::Permissions: crew_state::IsSet,
    S::AddedAt: crew_state::IsSet,
    S::Role: crew_state::IsSet,
    S::Member: crew_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Crew<'a> {
        Crew {
            added_at: self._fields.0.unwrap(),
            member: self._fields.1.unwrap(),
            permissions: self._fields.2.unwrap(),
            role: self._fields.3.unwrap(),
            tier: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Crew<'a> {
        Crew {
            added_at: self._fields.0.unwrap(),
            member: self._fields.1.unwrap(),
            permissions: self._fields.2.unwrap(),
            role: self._fields.3.unwrap(),
            tier: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_atcr_hold_crew() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("io.atcr.hold.crew"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Crew member in a hold's embedded PDS. Grants access permissions to push blobs to the hold. Stored in the hold's embedded PDS (one record per member).",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("member"), SmolStr::new_static("role"),
                                SmolStr::new_static("permissions"),
                                SmolStr::new_static("addedAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("addedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "RFC3339 timestamp of when the member was added",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("member"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("DID of the crew member"),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("permissions"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Specific permissions granted to this member",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(64usize),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("role"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Member's role in the hold"),
                                    ),
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("tier"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Optional tier for quota limits (e.g., 'deckhand', 'bosun', 'quartermaster'). If empty, uses defaults.new_crew_tier from quotas.yaml.",
                                        ),
                                    ),
                                    max_length: Some(32usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}