// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: garden.lexicon.service
//
// 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};
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::garden_lexicon::service;
/// Declares XRPC methods available on a DID document service. The rkey is the service fragment ID without the # prefix (e.g., 'atproto_pds' for '#atproto_pds').

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "garden.lexicon.service",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Service<S: BosStr = DefaultStr> {
    ///Description of what this service provides.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Methods available on this service.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub methods: Option<Vec<service::Method<S>>>,
    ///The type of service being declared.
    pub service_type: S,
    ///URL templates for constructing web URLs from AT-URIs or record data. Useful for linking to web views of records.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url_templates: Option<Vec<service::UrlTemplate<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 ServiceGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Service<S>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Method<S: BosStr = DefaultStr> {
    ///Authentication methods supported by this method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_methods: Option<Vec<S>>,
    ///Whether this method is deprecated and should no longer be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<bool>,
    ///AT-URI pointing to a lexicon schema that defines this method.
    pub lexicon: AtUri<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct UrlTemplate<S: BosStr = DefaultStr> {
    ///NSIDs of collections this URL template applies to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collections: Option<Vec<Nsid<S>>>,
    ///Description of what this URL template is for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///URI template with placeholders for record data
    pub url: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

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

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

impl<S: BosStr> Collection for Service<S> {
    const NSID: &'static str = "garden.lexicon.service";
    type Record = ServiceRecord;
}

impl Collection for ServiceRecord {
    const NSID: &'static str = "garden.lexicon.service";
    type Record = ServiceRecord;
}

impl<S: BosStr> LexiconSchema for Service<S> {
    fn nsid() -> &'static str {
        "garden.lexicon.service"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_lexicon_service()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.service_type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("service_type"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Method<S> {
    fn nsid() -> &'static str {
        "garden.lexicon.service"
    }
    fn def_name() -> &'static str {
        "method"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_lexicon_service()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for UrlTemplate<S> {
    fn nsid() -> &'static str {
        "garden.lexicon.service"
    }
    fn def_name() -> &'static str {
        "urlTemplate"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_garden_lexicon_service()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.url;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 2000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 2000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Service<S> {
    /// Create a new builder for this type
    pub fn builder() -> ServiceBuilder<service_state::Empty, S> {
        ServiceBuilder::builder()
    }
}

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

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

impl<St: service_state::State, S: BosStr> ServiceBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: service_state::State, S: BosStr> ServiceBuilder<St, S> {
    /// Set the `methods` field (optional)
    pub fn methods(mut self, value: impl Into<Option<Vec<service::Method<S>>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `methods` field to an Option value (optional)
    pub fn maybe_methods(mut self, value: Option<Vec<service::Method<S>>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> ServiceBuilder<St, S>
where
    St: service_state::State,
    St::ServiceType: service_state::IsUnset,
{
    /// Set the `serviceType` field (required)
    pub fn service_type(
        mut self,
        value: impl Into<S>,
    ) -> ServiceBuilder<service_state::SetServiceType<St>, S> {
        self._fields.2 = Option::Some(value.into());
        ServiceBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: service_state::State, S: BosStr> ServiceBuilder<St, S> {
    /// Set the `urlTemplates` field (optional)
    pub fn url_templates(
        mut self,
        value: impl Into<Option<Vec<service::UrlTemplate<S>>>>,
    ) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `urlTemplates` field to an Option value (optional)
    pub fn maybe_url_templates(
        mut self,
        value: Option<Vec<service::UrlTemplate<S>>>,
    ) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> ServiceBuilder<St, S>
where
    St: service_state::State,
    St::ServiceType: service_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Service<S> {
        Service {
            description: self._fields.0,
            methods: self._fields.1,
            service_type: self._fields.2.unwrap(),
            url_templates: self._fields.3,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Service<S> {
        Service {
            description: self._fields.0,
            methods: self._fields.1,
            service_type: self._fields.2.unwrap(),
            url_templates: self._fields.3,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_garden_lexicon_service() -> 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("garden.lexicon.service"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Declares XRPC methods available on a DID document service. The rkey is the service fragment ID without the # prefix (e.g., 'atproto_pds' for '#atproto_pds').",
                        ),
                    ),
                    key: Some(CowStr::new_static("any")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("serviceType")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Description of what this service provides.",
                                        ),
                                    ),
                                    max_length: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("methods"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Methods available on this service."),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#method"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("serviceType"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("The type of service being declared."),
                                    ),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("urlTemplates"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "URL templates for constructing web URLs from AT-URIs or record data. Useful for linking to web views of records.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#urlTemplate"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("method"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("lexicon")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("authMethods"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "Authentication methods supported by this method.",
                                    ),
                                ),
                                items: LexArrayItem::String(LexString {
                                    max_length: Some(50usize),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("deprecated"),
                            LexObjectProperty::Boolean(LexBoolean {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("lexicon"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "AT-URI pointing to a lexicon schema that defines this method.",
                                    ),
                                ),
                                format: Some(LexStringFormat::AtUri),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("urlTemplate"),
                LexUserType::Object(LexObject {
                    required: Some(vec![SmolStr::new_static("url")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("collections"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "NSIDs of collections this URL template applies to.",
                                    ),
                                ),
                                items: LexArrayItem::String(LexString {
                                    format: Some(LexStringFormat::Nsid),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("description"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Description of what this URL template is for.",
                                    ),
                                ),
                                max_length: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("url"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "URI template with placeholders for record data",
                                    ),
                                ),
                                max_length: Some(2000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

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

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

impl<S: BosStr> Method<S> {
    /// Create a new builder for this type
    pub fn builder() -> MethodBuilder<method_state::Empty, S> {
        MethodBuilder::builder()
    }
}

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

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

impl<St: method_state::State, S: BosStr> MethodBuilder<St, S> {
    /// Set the `authMethods` field (optional)
    pub fn auth_methods(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `authMethods` field to an Option value (optional)
    pub fn maybe_auth_methods(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: method_state::State, S: BosStr> MethodBuilder<St, S> {
    /// Set the `deprecated` field (optional)
    pub fn deprecated(mut self, value: impl Into<Option<bool>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `deprecated` field to an Option value (optional)
    pub fn maybe_deprecated(mut self, value: Option<bool>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> MethodBuilder<St, S>
where
    St: method_state::State,
    St::Lexicon: method_state::IsUnset,
{
    /// Set the `lexicon` field (required)
    pub fn lexicon(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> MethodBuilder<method_state::SetLexicon<St>, S> {
        self._fields.2 = Option::Some(value.into());
        MethodBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> MethodBuilder<St, S>
where
    St: method_state::State,
    St::Lexicon: method_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Method<S> {
        Method {
            auth_methods: self._fields.0,
            deprecated: self._fields.1,
            lexicon: 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>>) -> Method<S> {
        Method {
            auth_methods: self._fields.0,
            deprecated: self._fields.1,
            lexicon: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}