// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.simocracy.event
//
// 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};
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};
/// Tracks user interactions — chat messages, senate hearings launched, and individual sim comments during hearings.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Event<'a> {
    ///DID of the user who triggered the event
    #[serde(borrow)]
    pub actor_did: CowStr<'a>,
    ///The actual content — sim response for chat, sim opinion for comment
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub content: Option<CowStr<'a>>,
    pub created_at: Datetime,
    ///Title of the proposal (for hearing/comment events)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub proposal_title: Option<CowStr<'a>>,
    ///Hearing round: 1=evaluation, 2=response, 3=summary (for comment events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub round: Option<i64>,
    ///Names of sims involved
    #[serde(borrow)]
    pub sim_names: Vec<CowStr<'a>>,
    ///AT-URIs of sims involved
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub sim_uris: Option<Vec<CowStr<'a>>>,
    ///Event type: chat, hearing, or comment
    #[serde(borrow)]
    pub r#type: CowStr<'a>,
    ///User's message that prompted the response (for chat events)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub user_message: Option<CowStr<'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 EventGetRecordOutput<'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: Event<'a>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct EventRecord;
impl XrpcResp for EventRecord {
    const NSID: &'static str = "org.simocracy.event";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = EventGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

impl Collection for Event<'_> {
    const NSID: &'static str = "org.simocracy.event";
    type Record = EventRecord;
}

impl Collection for EventRecord {
    const NSID: &'static str = "org.simocracy.event";
    type Record = EventRecord;
}

impl<'a> LexiconSchema for Event<'a> {
    fn nsid() -> &'static str {
        "org.simocracy.event"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_simocracy_event()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.content {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 5000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("content"),
                        max: 5000usize,
                        actual: count,
                    });
                }
            }
        }
        if let Some(ref value) = self.proposal_title {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 500usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("proposal_title"),
                        max: 500usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.sim_names;
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("sim_names"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.sim_uris {
            #[allow(unused_comparisons)]
            if value.len() > 10usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("sim_uris"),
                    max: 10usize,
                    actual: value.len(),
                });
            }
        }
        if let Some(ref value) = self.user_message {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 2000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("user_message"),
                        max: 2000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

pub mod event_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 ActorDid;
        type CreatedAt;
        type SimNames;
        type Type;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type ActorDid = Unset;
        type CreatedAt = Unset;
        type SimNames = Unset;
        type Type = Unset;
    }
    ///State transition - sets the `actor_did` field to Set
    pub struct SetActorDid<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetActorDid<S> {}
    impl<S: State> State for SetActorDid<S> {
        type ActorDid = Set<members::actor_did>;
        type CreatedAt = S::CreatedAt;
        type SimNames = S::SimNames;
        type Type = S::Type;
    }
    ///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 ActorDid = S::ActorDid;
        type CreatedAt = Set<members::created_at>;
        type SimNames = S::SimNames;
        type Type = S::Type;
    }
    ///State transition - sets the `sim_names` field to Set
    pub struct SetSimNames<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSimNames<S> {}
    impl<S: State> State for SetSimNames<S> {
        type ActorDid = S::ActorDid;
        type CreatedAt = S::CreatedAt;
        type SimNames = Set<members::sim_names>;
        type Type = S::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetType<S> {}
    impl<S: State> State for SetType<S> {
        type ActorDid = S::ActorDid;
        type CreatedAt = S::CreatedAt;
        type SimNames = S::SimNames;
        type Type = Set<members::r#type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `actor_did` field
        pub struct actor_did(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `sim_names` field
        pub struct sim_names(());
        ///Marker type for the `type` field
        pub struct r#type(());
    }
}

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

impl<'a> Event<'a> {
    /// Create a new builder for this type
    pub fn new() -> EventBuilder<'a, event_state::Empty> {
        EventBuilder::new()
    }
}

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

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::ActorDid: event_state::IsUnset,
{
    /// Set the `actorDid` field (required)
    pub fn actor_did(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> EventBuilder<'a, event_state::SetActorDid<S>> {
        self._fields.0 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `content` field (optional)
    pub fn content(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `content` field to an Option value (optional)
    pub fn maybe_content(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `proposalTitle` field (optional)
    pub fn proposal_title(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `proposalTitle` field to an Option value (optional)
    pub fn maybe_proposal_title(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `round` field (optional)
    pub fn round(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `round` field to an Option value (optional)
    pub fn maybe_round(mut self, value: Option<i64>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::SimNames: event_state::IsUnset,
{
    /// Set the `simNames` field (required)
    pub fn sim_names(
        mut self,
        value: impl Into<Vec<CowStr<'a>>>,
    ) -> EventBuilder<'a, event_state::SetSimNames<S>> {
        self._fields.5 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `simUris` field (optional)
    pub fn sim_uris(mut self, value: impl Into<Option<Vec<CowStr<'a>>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `simUris` field to an Option value (optional)
    pub fn maybe_sim_uris(mut self, value: Option<Vec<CowStr<'a>>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::Type: event_state::IsUnset,
{
    /// Set the `type` field (required)
    pub fn r#type(
        mut self,
        value: impl Into<CowStr<'a>>,
    ) -> EventBuilder<'a, event_state::SetType<S>> {
        self._fields.7 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: event_state::State> EventBuilder<'a, S> {
    /// Set the `userMessage` field (optional)
    pub fn user_message(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.8 = value.into();
        self
    }
    /// Set the `userMessage` field to an Option value (optional)
    pub fn maybe_user_message(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<'a, S> EventBuilder<'a, S>
where
    S: event_state::State,
    S::ActorDid: event_state::IsSet,
    S::CreatedAt: event_state::IsSet,
    S::SimNames: event_state::IsSet,
    S::Type: event_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Event<'a> {
        Event {
            actor_did: self._fields.0.unwrap(),
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            proposal_title: self._fields.3,
            round: self._fields.4,
            sim_names: self._fields.5.unwrap(),
            sim_uris: self._fields.6,
            r#type: self._fields.7.unwrap(),
            user_message: self._fields.8,
            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>,
        >,
    ) -> Event<'a> {
        Event {
            actor_did: self._fields.0.unwrap(),
            content: self._fields.1,
            created_at: self._fields.2.unwrap(),
            proposal_title: self._fields.3,
            round: self._fields.4,
            sim_names: self._fields.5.unwrap(),
            sim_uris: self._fields.6,
            r#type: self._fields.7.unwrap(),
            user_message: self._fields.8,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_simocracy_event() -> 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("org.simocracy.event"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Tracks user interactions — chat messages, senate hearings launched, and individual sim comments during hearings.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("type"),
                                SmolStr::new_static("actorDid"),
                                SmolStr::new_static("simNames"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("actorDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "DID of the user who triggered the event",
                                        ),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("content"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "The actual content — sim response for chat, sim opinion for comment",
                                        ),
                                    ),
                                    max_graphemes: Some(5000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("proposalTitle"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Title of the proposal (for hearing/comment events)",
                                        ),
                                    ),
                                    max_graphemes: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("round"),
                                LexObjectProperty::Integer(LexInteger {
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("simNames"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Names of sims involved"),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("simUris"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("AT-URIs of sims involved"),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        ..Default::default()
                                    }),
                                    max_length: Some(10usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("type"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Event type: chat, hearing, or comment"),
                                    ),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("userMessage"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "User's message that prompted the response (for chat events)",
                                        ),
                                    ),
                                    max_graphemes: Some(2000usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}