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

#[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, Datetime, UriValue};
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};
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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Organization<'a> {
    ///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")]
    #[serde(borrow)]
    pub location: Option<StrongRef<'a>>,
    ///Legal or operational structures of the organization (e.g. 'nonprofit', 'ngo', 'government', 'social-enterprise', 'cooperative').
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub organization_type: Option<Vec<CowStr<'a>>>,
    ///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")]
    #[serde(borrow)]
    pub urls: Option<Vec<organization::UrlItem<'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 OrganizationGetRecordOutput<'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: Organization<'a>,
}

/// A labeled URL reference.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct UrlItem<'a> {
    ///Optional human-readable label for this URL (e.g. 'Support page', 'Donation page').
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub label: Option<CowStr<'a>>,
    ///The URL.
    #[serde(borrow)]
    pub url: UriValue<'a>,
}

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

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

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

impl Collection for Organization<'_> {
    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<'a> LexiconSchema for Organization<'a> {
    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<'a> LexiconSchema for UrlItem<'a> {
    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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedAt<S> {}
    impl<S: State> State for SetCreatedAt<S> {
        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<'a, S: organization_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Datetime>,
        Option<Datetime>,
        Option<StrongRef<'a>>,
        Option<Vec<CowStr<'a>>>,
        Option<Vec<organization::UrlItem<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

impl<'a, S: organization_state::State> OrganizationBuilder<'a, 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<'a, S: organization_state::State> OrganizationBuilder<'a, S> {
    /// Set the `location` field (optional)
    pub fn location(mut self, value: impl Into<Option<StrongRef<'a>>>) -> 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<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: organization_state::State> OrganizationBuilder<'a, S> {
    /// Set the `organizationType` field (optional)
    pub fn organization_type(
        mut self,
        value: impl Into<Option<Vec<CowStr<'a>>>>,
    ) -> 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<CowStr<'a>>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: organization_state::State> OrganizationBuilder<'a, S> {
    /// Set the `urls` field (optional)
    pub fn urls(
        mut self,
        value: impl Into<Option<Vec<organization::UrlItem<'a>>>>,
    ) -> 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<'a>>>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> OrganizationBuilder<'a, S>
where
    S: organization_state::State,
    S::CreatedAt: organization_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Organization<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Organization<'a> {
        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<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetUrl<S> {}
    impl<S: State> State for SetUrl<S> {
        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<'a, S: url_item_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (Option<CowStr<'a>>, Option<UriValue<'a>>),
    _lifetime: PhantomData<&'a ()>,
}

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

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

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

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

impl<'a, S> UrlItemBuilder<'a, S>
where
    S: url_item_state::State,
    S::Url: url_item_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> UrlItem<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> UrlItem<'a> {
        UrlItem {
            label: self._fields.0,
            url: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}