// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: sh.tangled.repo.branch
//
// 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::string::Datetime;
use jacquard_derive::{IntoStatic, lexicon, open_union};
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::sh_tangled::repo::branch;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Branch<'a> {
    #[serde(borrow)]
    pub name: CowStr<'a>,
    #[serde(borrow)]
    pub repo: CowStr<'a>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct BranchOutput<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub author: Option<branch::Signature<'a>>,
    ///Latest commit hash on this branch
    #[serde(borrow)]
    pub hash: CowStr<'a>,
    ///Whether this is the default branch
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_default: Option<bool>,
    ///Latest commit message
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub message: Option<CowStr<'a>>,
    ///Branch name
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///Short commit hash
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub short_hash: Option<CowStr<'a>>,
    ///Timestamp of latest commit
    pub when: Datetime,
}


#[open_union]
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic,
    IntoStatic
)]

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum BranchError<'a> {
    /// Repository not found or access denied
    #[serde(rename = "RepoNotFound")]
    RepoNotFound(Option<CowStr<'a>>),
    /// Branch not found
    #[serde(rename = "BranchNotFound")]
    BranchNotFound(Option<CowStr<'a>>),
    /// Invalid request parameters
    #[serde(rename = "InvalidRequest")]
    InvalidRequest(Option<CowStr<'a>>),
}

impl core::fmt::Display for BranchError<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::RepoNotFound(msg) => {
                write!(f, "RepoNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::BranchNotFound(msg) => {
                write!(f, "BranchNotFound")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::InvalidRequest(msg) => {
                write!(f, "InvalidRequest")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Signature<'a> {
    ///Author email
    #[serde(borrow)]
    pub email: CowStr<'a>,
    ///Author name
    #[serde(borrow)]
    pub name: CowStr<'a>,
    ///Author timestamp
    pub when: Datetime,
}

/// Response type for sh.tangled.repo.branch
pub struct BranchResponse;
impl jacquard_common::xrpc::XrpcResp for BranchResponse {
    const NSID: &'static str = "sh.tangled.repo.branch";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = BranchOutput<'de>;
    type Err<'de> = BranchError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for Branch<'a> {
    const NSID: &'static str = "sh.tangled.repo.branch";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Response = BranchResponse;
}

/// Endpoint type for sh.tangled.repo.branch
pub struct BranchRequest;
impl jacquard_common::xrpc::XrpcEndpoint for BranchRequest {
    const PATH: &'static str = "/xrpc/sh.tangled.repo.branch";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Query;
    type Request<'de> = Branch<'de>;
    type Response = BranchResponse;
}

impl<'a> LexiconSchema for Signature<'a> {
    fn nsid() -> &'static str {
        "sh.tangled.repo.branch"
    }
    fn def_name() -> &'static str {
        "signature"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_sh_tangled_repo_branch()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

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

impl<'a> Branch<'a> {
    /// Create a new builder for this type
    pub fn new() -> BranchBuilder<'a, branch_state::Empty> {
        BranchBuilder::new()
    }
}

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

impl<'a, S> BranchBuilder<'a, S>
where
    S: branch_state::State,
    S::Name: branch_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> BranchBuilder<'a, branch_state::SetName<S>> {
        self._fields.0 = Option::Some(value.into());
        BranchBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

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

impl<'a, S> BranchBuilder<'a, S>
where
    S: branch_state::State,
    S::Name: branch_state::IsSet,
    S::Repo: branch_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Branch<'a> {
        Branch {
            name: self._fields.0.unwrap(),
            repo: self._fields.1.unwrap(),
        }
    }
}

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

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

impl<'a> Signature<'a> {
    /// Create a new builder for this type
    pub fn new() -> SignatureBuilder<'a, signature_state::Empty> {
        SignatureBuilder::new()
    }
}

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

impl<'a, S> SignatureBuilder<'a, S>
where
    S: signature_state::State,
    S::Email: signature_state::IsUnset,
{
    /// Set the `email` field (required)
    pub fn email(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> SignatureBuilder<'a, signature_state::SetEmail<S>> {
        self._fields.0 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SignatureBuilder<'a, S>
where
    S: signature_state::State,
    S::Name: signature_state::IsUnset,
{
    /// Set the `name` field (required)
    pub fn name(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> SignatureBuilder<'a, signature_state::SetName<S>> {
        self._fields.1 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SignatureBuilder<'a, S>
where
    S: signature_state::State,
    S::When: signature_state::IsUnset,
{
    /// Set the `when` field (required)
    pub fn when(
        mut self,
        value: impl Into<Datetime>,
    ) -> SignatureBuilder<'a, signature_state::SetWhen<S>> {
        self._fields.2 = Option::Some(value.into());
        SignatureBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> SignatureBuilder<'a, S>
where
    S: signature_state::State,
    S::Name: signature_state::IsSet,
    S::When: signature_state::IsSet,
    S::Email: signature_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Signature<'a> {
        Signature {
            email: self._fields.0.unwrap(),
            name: self._fields.1.unwrap(),
            when: 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>,
        >,
    ) -> Signature<'a> {
        Signature {
            email: self._fields.0.unwrap(),
            name: self._fields.1.unwrap(),
            when: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_sh_tangled_repo_branch() -> 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("sh.tangled.repo.branch"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcQuery(LexXrpcQuery {
                    parameters: Some(
                        LexXrpcQueryParameter::Params(LexXrpcParameters {
                            required: Some(
                                vec![
                                    SmolStr::new_static("repo"), SmolStr::new_static("name")
                                ],
                            ),
                            properties: {
                                #[allow(unused_mut)]
                                let mut map = BTreeMap::new();
                                map.insert(
                                    SmolStr::new_static("name"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static("Branch name to get information for"),
                                        ),
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("repo"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Repository identifier in format 'did:plc:.../repoName'",
                                            ),
                                        ),
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("signature"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("name"), SmolStr::new_static("email"),
                            SmolStr::new_static("when")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("email"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Author email")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Author name")),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("when"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("Author timestamp")),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}