// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: at.inlay.pack
//
// 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::{AtUri, Nsid, 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};
use crate::at_inlay::pack;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Export<S: BosStr = DefaultStr> {
    ///AT-URI of the component record
    pub component: AtUri<S>,
    ///NSID of the type being exported
    pub r#type: Nsid<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A list of type to component exports

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "at.inlay.pack",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Pack<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Datetime>,
    ///Type to component mappings
    pub exports: Vec<pack::Export<S>>,
    ///Short slug for the pack (e.g. "core", "ui")
    pub name: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// 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 PackGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Pack<S>,
}

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

impl<S: BosStr> LexiconSchema for Export<S> {
    fn nsid() -> &'static str {
        "at.inlay.pack"
    }
    fn def_name() -> &'static str {
        "export"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_pack()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct PackRecord;
impl XrpcResp for PackRecord {
    const NSID: &'static str = "at.inlay.pack";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = PackGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Pack<S> {
    const NSID: &'static str = "at.inlay.pack";
    type Record = PackRecord;
}

impl Collection for PackRecord {
    const NSID: &'static str = "at.inlay.pack";
    type Record = PackRecord;
}

impl<S: BosStr> LexiconSchema for Pack<S> {
    fn nsid() -> &'static str {
        "at.inlay.pack"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_pack()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod export_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 Component;
        type Type;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Component = Unset;
        type Type = Unset;
    }
    ///State transition - sets the `component` field to Set
    pub struct SetComponent<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetComponent<St> {}
    impl<St: State> State for SetComponent<St> {
        type Component = Set<members::component>;
        type Type = St::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetType<St> {}
    impl<St: State> State for SetType<St> {
        type Component = St::Component;
        type Type = Set<members::r#type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `component` field
        pub struct component(());
        ///Marker type for the `type` field
        pub struct r#type(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ExportBuilder<St: export_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<AtUri<S>>, Option<Nsid<S>>),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Export<S> {
    /// Create a new builder for this type
    pub fn builder() -> ExportBuilder<export_state::Empty, S> {
        ExportBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ExportBuilder<St, S>
where
    St: export_state::State,
    St::Component: export_state::IsUnset,
{
    /// Set the `component` field (required)
    pub fn component(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> ExportBuilder<export_state::SetComponent<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ExportBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ExportBuilder<St, S>
where
    St: export_state::State,
    St::Type: export_state::IsUnset,
{
    /// Set the `type` field (required)
    pub fn r#type(
        mut self,
        value: impl Into<Nsid<S>>,
    ) -> ExportBuilder<export_state::SetType<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ExportBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ExportBuilder<St, S>
where
    St: export_state::State,
    St::Component: export_state::IsSet,
    St::Type: export_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Export<S> {
        Export {
            component: self._fields.0.unwrap(),
            r#type: self._fields.1.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Export<S> {
        Export {
            component: self._fields.0.unwrap(),
            r#type: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_at_inlay_pack() -> 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("at.inlay.pack"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("export"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("type"), SmolStr::new_static("component")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("component"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("AT-URI of the component record"),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("NSID of the type being exported"),
                                ),
                                format: Some(LexStringFormat::Nsid),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static("A list of type to component exports"),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("name"), SmolStr::new_static("exports")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("exports"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Type to component mappings"),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#export"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("name"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Short slug for the pack (e.g. \"core\", \"ui\")",
                                        ),
                                    ),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod pack_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 Exports;
        type Name;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Exports = Unset;
        type Name = Unset;
    }
    ///State transition - sets the `exports` field to Set
    pub struct SetExports<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetExports<St> {}
    impl<St: State> State for SetExports<St> {
        type Exports = Set<members::exports>;
        type Name = St::Name;
    }
    ///State transition - sets the `name` field to Set
    pub struct SetName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type Exports = St::Exports;
        type Name = Set<members::name>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `exports` field
        pub struct exports(());
        ///Marker type for the `name` field
        pub struct name(());
    }
}

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

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

impl<S: BosStr> Pack<S> {
    /// Create a new builder for this type
    pub fn builder() -> PackBuilder<pack_state::Empty, S> {
        PackBuilder::builder()
    }
}

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

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

impl<St: pack_state::State, S: BosStr> PackBuilder<St, S> {
    /// Set the `createdAt` field (optional)
    pub fn created_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `createdAt` field to an Option value (optional)
    pub fn maybe_created_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> PackBuilder<St, S>
where
    St: pack_state::State,
    St::Exports: pack_state::IsUnset,
{
    /// Set the `exports` field (required)
    pub fn exports(
        mut self,
        value: impl Into<Vec<pack::Export<S>>>,
    ) -> PackBuilder<pack_state::SetExports<St>, S> {
        self._fields.1 = Option::Some(value.into());
        PackBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PackBuilder<St, S>
where
    St: pack_state::State,
    St::Name: pack_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<S>,
    ) -> PackBuilder<pack_state::SetName<St>, S> {
        self._fields.2 = Option::Some(value.into());
        PackBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PackBuilder<St, S>
where
    St: pack_state::State,
    St::Exports: pack_state::IsSet,
    St::Name: pack_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Pack<S> {
        Pack {
            created_at: self._fields.0,
            exports: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Pack<S> {
        Pack {
            created_at: self._fields.0,
            exports: self._fields.1.unwrap(),
            name: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}