// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid};
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};
/// 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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Ref<'a> {
    ///The hex SHA-256 object ID this ref points to.
    #[serde(borrow)]
    pub object_id: CowStr<'a>,
    ///The full ref name, e.g. refs/heads/main.
    #[serde(borrow)]
    pub ref_name: CowStr<'a>,
    ///The repository name (path) on this DID account.
    #[serde(borrow)]
    pub repo: CowStr<'a>,
}

/// 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<'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: Ref<'a>,
}

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

/// 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<'de> = RefGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

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

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

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

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

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

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

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

impl<'a, S> RefBuilder<'a, S>
where
    S: ref_state::State,
    S::RefName: ref_state::IsSet,
    S::Repo: ref_state::IsSet,
    S::ObjectId: ref_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Ref<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Ref<'a> {
        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()
    }
}