// @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, 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};
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};
/// Tracks user interactions — chat messages, senate hearings launched, and individual sim comments during hearings.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "org.simocracy.event",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Event<S: BosStr = DefaultStr> {
    ///DID of the user who triggered the event
    pub actor_did: S,
    ///The actual content — sim response for chat, sim opinion for comment
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<S>,
    pub created_at: Datetime,
    ///Title of the proposal (for hearing/comment events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proposal_title: Option<S>,
    ///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
    pub sim_names: Vec<S>,
    ///AT-URIs of sims involved
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sim_uris: Option<Vec<S>>,
    ///Event type: chat, hearing, or comment
    pub r#type: S,
    ///User's message that prompted the response (for chat events)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_message: Option<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 EventGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Event<S>,
}

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

/// 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<S: BosStr> = EventGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Event<S> {
    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<S: BosStr> LexiconSchema for Event<S> {
    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<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetActorDid<St> {}
    impl<St: State> State for SetActorDid<St> {
        type ActorDid = Set<members::actor_did>;
        type CreatedAt = St::CreatedAt;
        type SimNames = St::SimNames;
        type Type = St::Type;
    }
    ///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 ActorDid = St::ActorDid;
        type CreatedAt = Set<members::created_at>;
        type SimNames = St::SimNames;
        type Type = St::Type;
    }
    ///State transition - sets the `sim_names` field to Set
    pub struct SetSimNames<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSimNames<St> {}
    impl<St: State> State for SetSimNames<St> {
        type ActorDid = St::ActorDid;
        type CreatedAt = St::CreatedAt;
        type SimNames = Set<members::sim_names>;
        type Type = St::Type;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetType<St> {}
    impl<St: State> State for SetType<St> {
        type ActorDid = St::ActorDid;
        type CreatedAt = St::CreatedAt;
        type SimNames = St::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<St: event_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<S>,
        Option<S>,
        Option<Datetime>,
        Option<S>,
        Option<i64>,
        Option<Vec<S>>,
        Option<Vec<S>>,
        Option<S>,
        Option<S>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

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

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

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

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

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

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

impl<St: event_state::State, S: BosStr> EventBuilder<St, S> {
    /// Set the `proposalTitle` field (optional)
    pub fn proposal_title(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: event_state::State, S: BosStr> EventBuilder<St, 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<St, S: BosStr> EventBuilder<St, S>
where
    St: event_state::State,
    St::SimNames: event_state::IsUnset,
{
    /// Set the `simNames` field (required)
    pub fn sim_names(
        mut self,
        value: impl Into<Vec<S>>,
    ) -> EventBuilder<event_state::SetSimNames<St>, S> {
        self._fields.5 = Option::Some(value.into());
        EventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: event_state::State, S: BosStr> EventBuilder<St, S> {
    /// Set the `simUris` field (optional)
    pub fn sim_uris(mut self, value: impl Into<Option<Vec<S>>>) -> 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<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

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

impl<St: event_state::State, S: BosStr> EventBuilder<St, S> {
    /// Set the `userMessage` field (optional)
    pub fn user_message(mut self, value: impl Into<Option<S>>) -> 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<S>) -> Self {
        self._fields.8 = value;
        self
    }
}

impl<St, S: BosStr> EventBuilder<St, S>
where
    St: event_state::State,
    St::ActorDid: event_state::IsSet,
    St::CreatedAt: event_state::IsSet,
    St::SimNames: event_state::IsSet,
    St::Type: event_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Event<S> {
        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<SmolStr, Data<S>>) -> Event<S> {
        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()
    }
}