// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: tech.lenooby09.didgit.ref
//
// 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, Cid};
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};
/// A did-git ref stored in an AT Protocol repository. Each record maps a repository name and ref name (e.g. refs/heads/main) to the hex SHA-256 object ID it points to.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "tech.lenooby09.didgit.ref",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Ref<S: BosStr = DefaultStr> {
    ///The hex SHA-256 object ID this ref points to.
    pub object_id: S,
    ///The full ref name, e.g. refs/heads/main.
    pub ref_name: S,
    ///The repository name (path) on this DID account.
    pub repo: 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 RefGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Ref<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct RefRecord;
impl XrpcResp for RefRecord {
    const NSID: &'static str = "tech.lenooby09.didgit.ref";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = RefGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Ref<S> {
    const NSID: &'static str = "tech.lenooby09.didgit.ref";
    type Record = RefRecord;
}

impl Collection for RefRecord {
    const NSID: &'static str = "tech.lenooby09.didgit.ref";
    type Record = RefRecord;
}

impl<S: BosStr> LexiconSchema for Ref<S> {
    fn nsid() -> &'static str {
        "tech.lenooby09.didgit.ref"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_tech_lenooby09_didgit_ref()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.object_id;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("object_id"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.ref_name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("ref_name"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.repo;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("repo"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod ref_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 ObjectId;
        type RefName;
        type Repo;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ObjectId = Unset;
        type RefName = Unset;
        type Repo = Unset;
    }
    ///State transition - sets the `object_id` field to Set
    pub struct SetObjectId<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetObjectId<St> {}
    impl<St: State> State for SetObjectId<St> {
        type ObjectId = Set<members::object_id>;
        type RefName = St::RefName;
        type Repo = St::Repo;
    }
    ///State transition - sets the `ref_name` field to Set
    pub struct SetRefName<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRefName<St> {}
    impl<St: State> State for SetRefName<St> {
        type ObjectId = St::ObjectId;
        type RefName = Set<members::ref_name>;
        type Repo = St::Repo;
    }
    ///State transition - sets the `repo` field to Set
    pub struct SetRepo<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRepo<St> {}
    impl<St: State> State for SetRepo<St> {
        type ObjectId = St::ObjectId;
        type RefName = St::RefName;
        type Repo = Set<members::repo>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `object_id` field
        pub struct object_id(());
        ///Marker type for the `ref_name` field
        pub struct ref_name(());
        ///Marker type for the `repo` field
        pub struct repo(());
    }
}

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

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

impl<S: BosStr> Ref<S> {
    /// Create a new builder for this type
    pub fn builder() -> RefBuilder<ref_state::Empty, S> {
        RefBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> RefBuilder<St, S>
where
    St: ref_state::State,
    St::ObjectId: ref_state::IsUnset,
{
    /// Set the `objectId` field (required)
    pub fn object_id(
        mut self,
        value: impl Into<S>,
    ) -> RefBuilder<ref_state::SetObjectId<St>, S> {
        self._fields.0 = Option::Some(value.into());
        RefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RefBuilder<St, S>
where
    St: ref_state::State,
    St::RefName: ref_state::IsUnset,
{
    /// Set the `refName` field (required)
    pub fn ref_name(
        mut self,
        value: impl Into<S>,
    ) -> RefBuilder<ref_state::SetRefName<St>, S> {
        self._fields.1 = Option::Some(value.into());
        RefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RefBuilder<St, S>
where
    St: ref_state::State,
    St::Repo: ref_state::IsUnset,
{
    /// Set the `repo` field (required)
    pub fn repo(mut self, value: impl Into<S>) -> RefBuilder<ref_state::SetRepo<St>, S> {
        self._fields.2 = Option::Some(value.into());
        RefBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> RefBuilder<St, S>
where
    St: ref_state::State,
    St::ObjectId: ref_state::IsSet,
    St::RefName: ref_state::IsSet,
    St::Repo: ref_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Ref<S> {
        Ref {
            object_id: self._fields.0.unwrap(),
            ref_name: self._fields.1.unwrap(),
            repo: 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>>) -> Ref<S> {
        Ref {
            object_id: self._fields.0.unwrap(),
            ref_name: self._fields.1.unwrap(),
            repo: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_tech_lenooby09_didgit_ref() -> 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("tech.lenooby09.didgit.ref"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A did-git ref stored in an AT Protocol repository. Each record maps a repository name and ref name (e.g. refs/heads/main) to the hex SHA-256 object ID it points to.",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("repo"), SmolStr::new_static("refName"),
                                SmolStr::new_static("objectId")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("objectId"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The hex SHA-256 object ID this ref points to.",
                                        ),
                                    ),
                                    max_length: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("refName"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The full ref name, e.g. refs/heads/main.",
                                        ),
                                    ),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("repo"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The repository name (path) on this DID account.",
                                        ),
                                    ),
                                    max_length: Some(512usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}