// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.certified.actor.organization
//
// 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, Datetime, UriValue};
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::com_atproto::repo::strong_ref::StrongRef;
use crate::app_certified::actor::organization;
/// Extended metadata for an organization actor. Complements the base actor profile with organization-specific fields like legal structure and reference links.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.certified.actor.organization",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Organization<S: BosStr = DefaultStr> {
    ///Client-declared timestamp when this record was originally created.
    pub created_at: Datetime,
    ///When the organization was established. Stored as datetime per ATProto conventions (no date-only format exists). Clients should use midnight UTC (e.g., '2005-01-01T00:00:00.000Z'); consumers should treat only the date portion as canonical.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub founded_date: Option<Datetime>,
    ///A strong reference to the location where the organization is based. The record referenced must conform with the lexicon app.certified.location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<StrongRef<S>>,
    ///Legal or operational structures of the organization (e.g. 'nonprofit', 'ngo', 'government', 'social-enterprise', 'cooperative').
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_type: Option<Vec<S>>,
    ///Additional reference URLs (social media profiles, contact pages, donation links, etc.) with a display label for each URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub urls: Option<Vec<organization::UrlItem<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 OrganizationGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Organization<S>,
}

/// A labeled URL reference.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct UrlItem<S: BosStr = DefaultStr> {
    ///Optional human-readable label for this URL (e.g. 'Support page', 'Donation page').
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<S>,
    ///The URL.
    pub url: UriValue<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct OrganizationRecord;
impl XrpcResp for OrganizationRecord {
    const NSID: &'static str = "app.certified.actor.organization";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = OrganizationGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Organization<S> {
    const NSID: &'static str = "app.certified.actor.organization";
    type Record = OrganizationRecord;
}

impl Collection for OrganizationRecord {
    const NSID: &'static str = "app.certified.actor.organization";
    type Record = OrganizationRecord;
}

impl<S: BosStr> LexiconSchema for Organization<S> {
    fn nsid() -> &'static str {
        "app.certified.actor.organization"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_certified_actor_organization()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.organization_type {
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("organization_type"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for UrlItem<S> {
    fn nsid() -> &'static str {
        "app.certified.actor.organization"
    }
    fn def_name() -> &'static str {
        "urlItem"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_certified_actor_organization()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.label {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 640usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("label"),
                    max: 640usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.label {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("label"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.url;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("url"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.url;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2048usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("url"),
                        max: 2048usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Organization<S> {
    /// Create a new builder for this type
    pub fn builder() -> OrganizationBuilder<organization_state::Empty, S> {
        OrganizationBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> OrganizationBuilder<St, S>
where
    St: organization_state::State,
    St::CreatedAt: organization_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> OrganizationBuilder<organization_state::SetCreatedAt<St>, S> {
        self._fields.0 = Option::Some(value.into());
        OrganizationBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: organization_state::State, S: BosStr> OrganizationBuilder<St, S> {
    /// Set the `foundedDate` field (optional)
    pub fn founded_date(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `foundedDate` field to an Option value (optional)
    pub fn maybe_founded_date(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: organization_state::State, S: BosStr> OrganizationBuilder<St, S> {
    /// Set the `location` field (optional)
    pub fn location(mut self, value: impl Into<Option<StrongRef<S>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `location` field to an Option value (optional)
    pub fn maybe_location(mut self, value: Option<StrongRef<S>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: organization_state::State, S: BosStr> OrganizationBuilder<St, S> {
    /// Set the `organizationType` field (optional)
    pub fn organization_type(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `organizationType` field to an Option value (optional)
    pub fn maybe_organization_type(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: organization_state::State, S: BosStr> OrganizationBuilder<St, S> {
    /// Set the `urls` field (optional)
    pub fn urls(
        mut self,
        value: impl Into<Option<Vec<organization::UrlItem<S>>>>,
    ) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `urls` field to an Option value (optional)
    pub fn maybe_urls(mut self, value: Option<Vec<organization::UrlItem<S>>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> OrganizationBuilder<St, S>
where
    St: organization_state::State,
    St::CreatedAt: organization_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Organization<S> {
        Organization {
            created_at: self._fields.0.unwrap(),
            founded_date: self._fields.1,
            location: self._fields.2,
            organization_type: self._fields.3,
            urls: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Organization<S> {
        Organization {
            created_at: self._fields.0.unwrap(),
            founded_date: self._fields.1,
            location: self._fields.2,
            organization_type: self._fields.3,
            urls: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_certified_actor_organization() -> 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("app.certified.actor.organization"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Extended metadata for an organization actor. Complements the base actor profile with organization-specific fields like legal structure and reference links.",
                        ),
                    ),
                    key: Some(CowStr::new_static("literal:self")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("createdAt")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Client-declared timestamp when this record was originally created.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("foundedDate"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "When the organization was established. Stored as datetime per ATProto conventions (no date-only format exists). Clients should use midnight UTC (e.g., '2005-01-01T00:00:00.000Z'); consumers should treat only the date portion as canonical.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("location"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("com.atproto.repo.strongRef"),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("organizationType"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Legal or operational structures of the organization (e.g. 'nonprofit', 'ngo', 'government', 'social-enterprise', 'cooperative').",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        max_length: Some(128usize),
                                        max_graphemes: Some(100usize),
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("urls"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Additional reference URLs (social media profiles, contact pages, donation links, etc.) with a display label for each URL.",
                                        ),
                                    ),
                                    items: LexArrayItem::Ref(LexRef {
                                        r#ref: CowStr::new_static("#urlItem"),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("urlItem"),
                LexUserType::Object(LexObject {
                    description: Some(CowStr::new_static("A labeled URL reference.")),
                    required: Some(vec![SmolStr::new_static("url")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("label"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Optional human-readable label for this URL (e.g. 'Support page', 'Donation page').",
                                    ),
                                ),
                                max_length: Some(640usize),
                                max_graphemes: Some(64usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("url"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("The URL.")),
                                format: Some(LexStringFormat::Uri),
                                max_length: Some(10000usize),
                                max_graphemes: Some(2048usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

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

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

impl<S: BosStr> UrlItem<S> {
    /// Create a new builder for this type
    pub fn builder() -> UrlItemBuilder<url_item_state::Empty, S> {
        UrlItemBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> UrlItemBuilder<St, S>
where
    St: url_item_state::State,
    St::Url: url_item_state::IsUnset,
{
    /// Set the `url` field (required)
    pub fn url(
        mut self,
        value: impl Into<UriValue<S>>,
    ) -> UrlItemBuilder<url_item_state::SetUrl<St>, S> {
        self._fields.1 = Option::Some(value.into());
        UrlItemBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> UrlItemBuilder<St, S>
where
    St: url_item_state::State,
    St::Url: url_item_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> UrlItem<S> {
        UrlItem {
            label: self._fields.0,
            url: self._fields.1.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>>) -> UrlItem<S> {
        UrlItem {
            label: self._fields.0,
            url: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}