// @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, 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::string::Datetime;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, 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", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Branch<S: BosStr = DefaultStr> {
    pub name: S,
    pub repo: S,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct BranchOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<branch::Signature<S>>,
    ///Latest commit hash on this branch
    pub hash: S,
    ///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")]
    pub message: Option<S>,
    ///Branch name
    pub name: S,
    ///Short commit hash
    #[serde(skip_serializing_if = "Option::is_none")]
    pub short_hash: Option<S>,
    ///Timestamp of latest commit
    pub when: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


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

#[serde(tag = "error", content = "message")]
pub enum BranchError {
    /// Repository not found or access denied
    #[serde(rename = "RepoNotFound")]
    RepoNotFound(Option<SmolStr>),
    /// Branch not found
    #[serde(rename = "BranchNotFound")]
    BranchNotFound(Option<SmolStr>),
    /// Invalid request parameters
    #[serde(rename = "InvalidRequest")]
    InvalidRequest(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

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::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Signature<S: BosStr = DefaultStr> {
    ///Author email
    pub email: S,
    ///Author name
    pub name: S,
    ///Author timestamp
    pub when: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/** Response marker for the `sh.tangled.repo.branch` query.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `BranchOutput<S>` for this endpoint.*/
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<S: BosStr> = BranchOutput<S>;
    type Err = BranchError;
}

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

/** Endpoint marker for the `sh.tangled.repo.branch` query.

Path: `/xrpc/sh.tangled.repo.branch`. The request payload type is `Branch<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
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<S: BosStr> = Branch<S>;
    type Response = BranchResponse;
}

impl<S: BosStr> LexiconSchema for Signature<S> {
    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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetName<St> {}
    impl<St: State> State for SetName<St> {
        type Name = Set<members::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 Name = St::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<St: branch_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

impl<St, S: BosStr> BranchBuilder<St, S>
where
    St: branch_state::State,
    St::Name: branch_state::IsSet,
    St::Repo: branch_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Branch<S> {
        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 Email;
        type Name;
        type When;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Email = Unset;
        type Name = Unset;
        type When = Unset;
    }
    ///State transition - sets the `email` field to Set
    pub struct SetEmail<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetEmail<St> {}
    impl<St: State> State for SetEmail<St> {
        type Email = Set<members::email>;
        type Name = St::Name;
        type When = St::When;
    }
    ///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 Email = St::Email;
        type Name = Set<members::name>;
        type When = St::When;
    }
    ///State transition - sets the `when` field to Set
    pub struct SetWhen<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetWhen<St> {}
    impl<St: State> State for SetWhen<St> {
        type Email = St::Email;
        type Name = St::Name;
        type When = Set<members::when>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `email` field
        pub struct email(());
        ///Marker type for the `name` field
        pub struct name(());
        ///Marker type for the `when` field
        pub struct when(());
    }
}

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

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

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

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

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

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

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

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

impl<St, S: BosStr> SignatureBuilder<St, S>
where
    St: signature_state::State,
    St::Email: signature_state::IsSet,
    St::Name: signature_state::IsSet,
    St::When: signature_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Signature<S> {
        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<SmolStr, Data<S>>,
    ) -> Signature<S> {
        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()
    }
}