// @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, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
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::types::value::Data;
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).

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.atcr.hold.crew",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Crew<S: BosStr = DefaultStr> {
    ///RFC3339 timestamp of when the member was added
    pub added_at: Datetime,
    ///DID of the crew member
    pub member: Did<S>,
    ///Specific permissions granted to this member
    pub permissions: Vec<S>,
    ///Member's role in the hold
    pub role: CrewRole<S>,
    ///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")]
    pub tier: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Member's role in the hold

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CrewRole<S: BosStr = DefaultStr> {
    Owner,
    Admin,
    Write,
    Read,
    Other(S),
}

impl<S: BosStr> CrewRole<S> {
    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(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "owner" => Self::Owner,
            "admin" => Self::Admin,
            "write" => Self::Write,
            "read" => Self::Read,
            _ => Self::Other(s),
        }
    }
}

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

impl<S: BosStr> AsRef<str> for CrewRole<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for CrewRole<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for CrewRole<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for CrewRole<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = CrewRole<S::Output>;
    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<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Crew<S>,
}

impl<S: BosStr> Crew<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, CrewRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

/// 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<S: BosStr> = CrewGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<CrewGetRecordOutput<S>> for Crew<S> {
    fn from(output: CrewGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Crew<S> {
    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<S: BosStr> LexiconSchema for Crew<S> {
    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 AddedAt;
        type Member;
        type Permissions;
        type Role;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type AddedAt = Unset;
        type Member = Unset;
        type Permissions = Unset;
        type Role = Unset;
    }
    ///State transition - sets the `added_at` field to Set
    pub struct SetAddedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAddedAt<St> {}
    impl<St: State> State for SetAddedAt<St> {
        type AddedAt = Set<members::added_at>;
        type Member = St::Member;
        type Permissions = St::Permissions;
        type Role = St::Role;
    }
    ///State transition - sets the `member` field to Set
    pub struct SetMember<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetMember<St> {}
    impl<St: State> State for SetMember<St> {
        type AddedAt = St::AddedAt;
        type Member = Set<members::member>;
        type Permissions = St::Permissions;
        type Role = St::Role;
    }
    ///State transition - sets the `permissions` field to Set
    pub struct SetPermissions<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPermissions<St> {}
    impl<St: State> State for SetPermissions<St> {
        type AddedAt = St::AddedAt;
        type Member = St::Member;
        type Permissions = Set<members::permissions>;
        type Role = St::Role;
    }
    ///State transition - sets the `role` field to Set
    pub struct SetRole<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRole<St> {}
    impl<St: State> State for SetRole<St> {
        type AddedAt = St::AddedAt;
        type Member = St::Member;
        type Permissions = St::Permissions;
        type Role = Set<members::role>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `added_at` field
        pub struct added_at(());
        ///Marker type for the `member` field
        pub struct member(());
        ///Marker type for the `permissions` field
        pub struct permissions(());
        ///Marker type for the `role` field
        pub struct role(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CrewBuilder<St: crew_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<Did<S>>,
        Option<Vec<S>>,
        Option<CrewRole<S>>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

impl Crew<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> CrewBuilder<crew_state::Empty, DefaultStr> {
        CrewBuilder::new()
    }
}

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

impl CrewBuilder<crew_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        CrewBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None, None),
            _type: PhantomData,
        }
    }
}

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

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

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

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

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

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

impl<St, S: BosStr> CrewBuilder<St, S>
where
    St: crew_state::State,
    St::AddedAt: crew_state::IsSet,
    St::Member: crew_state::IsSet,
    St::Permissions: crew_state::IsSet,
    St::Role: crew_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Crew<S> {
        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<SmolStr, Data<S>>) -> Crew<S> {
        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()
    }
}