// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: tools.ozone.moderation.emitEvent
//
// 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;
use jacquard_common::types::string::{Did, Cid};
use jacquard_derive::{IntoStatic, lexicon, open_union};
use serde::{Serialize, Deserialize};
use crate::com_atproto::admin::RepoRef;
use crate::com_atproto::repo::strong_ref::StrongRef;
use crate::tools_ozone::moderation::AccountEvent;
use crate::tools_ozone::moderation::AgeAssuranceEvent;
use crate::tools_ozone::moderation::AgeAssuranceOverrideEvent;
use crate::tools_ozone::moderation::AgeAssurancePurgeEvent;
use crate::tools_ozone::moderation::CancelScheduledTakedownEvent;
use crate::tools_ozone::moderation::IdentityEvent;
use crate::tools_ozone::moderation::ModEventAcknowledge;
use crate::tools_ozone::moderation::ModEventComment;
use crate::tools_ozone::moderation::ModEventDivert;
use crate::tools_ozone::moderation::ModEventEmail;
use crate::tools_ozone::moderation::ModEventEscalate;
use crate::tools_ozone::moderation::ModEventLabel;
use crate::tools_ozone::moderation::ModEventMute;
use crate::tools_ozone::moderation::ModEventMuteReporter;
use crate::tools_ozone::moderation::ModEventPriorityScore;
use crate::tools_ozone::moderation::ModEventReport;
use crate::tools_ozone::moderation::ModEventResolveAppeal;
use crate::tools_ozone::moderation::ModEventReverseTakedown;
use crate::tools_ozone::moderation::ModEventTag;
use crate::tools_ozone::moderation::ModEventTakedown;
use crate::tools_ozone::moderation::ModEventUnmute;
use crate::tools_ozone::moderation::ModEventUnmuteReporter;
use crate::tools_ozone::moderation::ModEventView;
use crate::tools_ozone::moderation::ModTool;
use crate::tools_ozone::moderation::RecordEvent;
use crate::tools_ozone::moderation::RevokeAccountCredentialsEvent;
use crate::tools_ozone::moderation::ScheduleTakedownEvent;

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct EmitEvent<'a> {
    #[serde(borrow)]
    pub created_by: Did<'a>,
    #[serde(borrow)]
    pub event: EmitEventEvent<'a>,
    ///An optional external ID for the event, used to deduplicate events from external systems. Fails when an event of same type with the same external ID exists for the same subject.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub external_id: Option<CowStr<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub mod_tool: Option<ModTool<'a>>,
    #[serde(borrow)]
    pub subject: EmitEventSubject<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub subject_blob_cids: Option<Vec<Cid<'a>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum EmitEventEvent<'a> {
    #[serde(rename = "tools.ozone.moderation.defs#modEventTakedown")]
    ModEventTakedown(Box<ModEventTakedown<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventAcknowledge")]
    ModEventAcknowledge(Box<ModEventAcknowledge<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventEscalate")]
    ModEventEscalate(Box<ModEventEscalate<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventComment")]
    ModEventComment(Box<ModEventComment<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventLabel")]
    ModEventLabel(Box<ModEventLabel<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventReport")]
    ModEventReport(Box<ModEventReport<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventMute")]
    ModEventMute(Box<ModEventMute<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventUnmute")]
    ModEventUnmute(Box<ModEventUnmute<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventMuteReporter")]
    ModEventMuteReporter(Box<ModEventMuteReporter<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventUnmuteReporter")]
    ModEventUnmuteReporter(Box<ModEventUnmuteReporter<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventReverseTakedown")]
    ModEventReverseTakedown(Box<ModEventReverseTakedown<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventResolveAppeal")]
    ModEventResolveAppeal(Box<ModEventResolveAppeal<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventEmail")]
    ModEventEmail(Box<ModEventEmail<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventDivert")]
    ModEventDivert(Box<ModEventDivert<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventTag")]
    ModEventTag(Box<ModEventTag<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#accountEvent")]
    AccountEvent(Box<AccountEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#identityEvent")]
    IdentityEvent(Box<IdentityEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#recordEvent")]
    RecordEvent(Box<RecordEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#modEventPriorityScore")]
    ModEventPriorityScore(Box<ModEventPriorityScore<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#ageAssuranceEvent")]
    AgeAssuranceEvent(Box<AgeAssuranceEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#ageAssuranceOverrideEvent")]
    AgeAssuranceOverrideEvent(Box<AgeAssuranceOverrideEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#ageAssurancePurgeEvent")]
    AgeAssurancePurgeEvent(Box<AgeAssurancePurgeEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#revokeAccountCredentialsEvent")]
    RevokeAccountCredentialsEvent(Box<RevokeAccountCredentialsEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#scheduleTakedownEvent")]
    ScheduleTakedownEvent(Box<ScheduleTakedownEvent<'a>>),
    #[serde(rename = "tools.ozone.moderation.defs#cancelScheduledTakedownEvent")]
    CancelScheduledTakedownEvent(Box<CancelScheduledTakedownEvent<'a>>),
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum EmitEventSubject<'a> {
    #[serde(rename = "com.atproto.admin.defs#repoRef")]
    RepoRef(Box<RepoRef<'a>>),
    #[serde(rename = "com.atproto.repo.strongRef")]
    StrongRef(Box<StrongRef<'a>>),
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct EmitEventOutput<'a> {
    #[serde(flatten)]
    #[serde(borrow)]
    pub value: ModEventView<'a>,
}


#[open_union]
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic,
    IntoStatic
)]

#[serde(tag = "error", content = "message")]
#[serde(bound(deserialize = "'de: 'a"))]
pub enum EmitEventError<'a> {
    #[serde(rename = "SubjectHasAction")]
    SubjectHasAction(Option<CowStr<'a>>),
    /// An event with the same external ID already exists for the subject.
    #[serde(rename = "DuplicateExternalId")]
    DuplicateExternalId(Option<CowStr<'a>>),
}

impl core::fmt::Display for EmitEventError<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::SubjectHasAction(msg) => {
                write!(f, "SubjectHasAction")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::DuplicateExternalId(msg) => {
                write!(f, "DuplicateExternalId")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

/// Response type for tools.ozone.moderation.emitEvent
pub struct EmitEventResponse;
impl jacquard_common::xrpc::XrpcResp for EmitEventResponse {
    const NSID: &'static str = "tools.ozone.moderation.emitEvent";
    const ENCODING: &'static str = "application/json";
    type Output<'de> = EmitEventOutput<'de>;
    type Err<'de> = EmitEventError<'de>;
}

impl<'a> jacquard_common::xrpc::XrpcRequest for EmitEvent<'a> {
    const NSID: &'static str = "tools.ozone.moderation.emitEvent";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = EmitEventResponse;
}

/// Endpoint type for tools.ozone.moderation.emitEvent
pub struct EmitEventRequest;
impl jacquard_common::xrpc::XrpcEndpoint for EmitEventRequest {
    const PATH: &'static str = "/xrpc/tools.ozone.moderation.emitEvent";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<'de> = EmitEvent<'de>;
    type Response = EmitEventResponse;
}

pub mod emit_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 CreatedBy;
        type Event;
        type Subject;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedBy = Unset;
        type Event = Unset;
        type Subject = Unset;
    }
    ///State transition - sets the `created_by` field to Set
    pub struct SetCreatedBy<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetCreatedBy<S> {}
    impl<S: State> State for SetCreatedBy<S> {
        type CreatedBy = Set<members::created_by>;
        type Event = S::Event;
        type Subject = S::Subject;
    }
    ///State transition - sets the `event` field to Set
    pub struct SetEvent<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetEvent<S> {}
    impl<S: State> State for SetEvent<S> {
        type CreatedBy = S::CreatedBy;
        type Event = Set<members::event>;
        type Subject = S::Subject;
    }
    ///State transition - sets the `subject` field to Set
    pub struct SetSubject<S: State = Empty>(PhantomData<fn() -> S>);
    impl<S: State> sealed::Sealed for SetSubject<S> {}
    impl<S: State> State for SetSubject<S> {
        type CreatedBy = S::CreatedBy;
        type Event = S::Event;
        type Subject = Set<members::subject>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_by` field
        pub struct created_by(());
        ///Marker type for the `event` field
        pub struct event(());
        ///Marker type for the `subject` field
        pub struct subject(());
    }
}

/// Builder for constructing an instance of this type
pub struct EmitEventBuilder<'a, S: emit_event_state::State> {
    _state: PhantomData<fn() -> S>,
    _fields: (
        Option<Did<'a>>,
        Option<EmitEventEvent<'a>>,
        Option<CowStr<'a>>,
        Option<ModTool<'a>>,
        Option<EmitEventSubject<'a>>,
        Option<Vec<Cid<'a>>>,
    ),
    _lifetime: PhantomData<&'a ()>,
}

impl<'a> EmitEvent<'a> {
    /// Create a new builder for this type
    pub fn new() -> EmitEventBuilder<'a, emit_event_state::Empty> {
        EmitEventBuilder::new()
    }
}

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

impl<'a, S> EmitEventBuilder<'a, S>
where
    S: emit_event_state::State,
    S::CreatedBy: emit_event_state::IsUnset,
{
    /// Set the `createdBy` field (required)
    pub fn created_by(
        mut self,
        value: impl Into<Did<'a>>,
    ) -> EmitEventBuilder<'a, emit_event_state::SetCreatedBy<S>> {
        self._fields.0 = Option::Some(value.into());
        EmitEventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S> EmitEventBuilder<'a, S>
where
    S: emit_event_state::State,
    S::Event: emit_event_state::IsUnset,
{
    /// Set the `event` field (required)
    pub fn event(
        mut self,
        value: impl Into<EmitEventEvent<'a>>,
    ) -> EmitEventBuilder<'a, emit_event_state::SetEvent<S>> {
        self._fields.1 = Option::Some(value.into());
        EmitEventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: emit_event_state::State> EmitEventBuilder<'a, S> {
    /// Set the `externalId` field (optional)
    pub fn external_id(mut self, value: impl Into<Option<CowStr<'a>>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `externalId` field to an Option value (optional)
    pub fn maybe_external_id(mut self, value: Option<CowStr<'a>>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<'a, S: emit_event_state::State> EmitEventBuilder<'a, S> {
    /// Set the `modTool` field (optional)
    pub fn mod_tool(mut self, value: impl Into<Option<ModTool<'a>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `modTool` field to an Option value (optional)
    pub fn maybe_mod_tool(mut self, value: Option<ModTool<'a>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<'a, S> EmitEventBuilder<'a, S>
where
    S: emit_event_state::State,
    S::Subject: emit_event_state::IsUnset,
{
    /// Set the `subject` field (required)
    pub fn subject(
        mut self,
        value: impl Into<EmitEventSubject<'a>>,
    ) -> EmitEventBuilder<'a, emit_event_state::SetSubject<S>> {
        self._fields.4 = Option::Some(value.into());
        EmitEventBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, S: emit_event_state::State> EmitEventBuilder<'a, S> {
    /// Set the `subjectBlobCids` field (optional)
    pub fn subject_blob_cids(mut self, value: impl Into<Option<Vec<Cid<'a>>>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `subjectBlobCids` field to an Option value (optional)
    pub fn maybe_subject_blob_cids(mut self, value: Option<Vec<Cid<'a>>>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<'a, S> EmitEventBuilder<'a, S>
where
    S: emit_event_state::State,
    S::CreatedBy: emit_event_state::IsSet,
    S::Event: emit_event_state::IsSet,
    S::Subject: emit_event_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> EmitEvent<'a> {
        EmitEvent {
            created_by: self._fields.0.unwrap(),
            event: self._fields.1.unwrap(),
            external_id: self._fields.2,
            mod_tool: self._fields.3,
            subject: self._fields.4.unwrap(),
            subject_blob_cids: self._fields.5,
            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>,
        >,
    ) -> EmitEvent<'a> {
        EmitEvent {
            created_by: self._fields.0.unwrap(),
            event: self._fields.1.unwrap(),
            external_id: self._fields.2,
            mod_tool: self._fields.3,
            subject: self._fields.4.unwrap(),
            subject_blob_cids: self._fields.5,
            extra_data: Some(extra_data),
        }
    }
}