// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: place.stream.server.createWebhook
//
// 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};
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::string::UriValue;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, open_union};
use serde::{Serialize, Deserialize};
use crate::place_stream::server::RewriteRule;
use crate::place_stream::server::Webhook;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateWebhook<S: BosStr = DefaultStr> {
    ///Whether this webhook should be active upon creation.  Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default = "_default_create_webhook_active")]
    pub active: Option<bool>,
    ///A description of what this webhook is used for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///The types of events this webhook should receive.
    pub events: Vec<S>,
    ///Words to filter out from chat messages. Messages containing any of these words will not be forwarded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mute_words: Option<Vec<S>>,
    ///A user-friendly name for this webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<S>,
    ///Text to prepend to webhook messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<S>,
    ///Text replacement rules for webhook messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rewrite: Option<Vec<RewriteRule<S>>>,
    ///Text to append to webhook messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<S>,
    ///The webhook URL where events will be sent.
    pub url: UriValue<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateWebhookOutput<S: BosStr = DefaultStr> {
    pub webhook: Webhook<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


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

#[serde(tag = "error", content = "message")]
pub enum CreateWebhookError {
    /// The provided webhook URL is invalid or unreachable.
    #[serde(rename = "InvalidUrl")]
    InvalidUrl(Option<SmolStr>),
    /// A webhook with this URL already exists for this user.
    #[serde(rename = "DuplicateWebhook")]
    DuplicateWebhook(Option<SmolStr>),
    /// The user has reached their maximum number of webhooks.
    #[serde(rename = "TooManyWebhooks")]
    TooManyWebhooks(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for CreateWebhookError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidUrl(msg) => {
                write!(f, "InvalidUrl")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::DuplicateWebhook(msg) => {
                write!(f, "DuplicateWebhook")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::TooManyWebhooks(msg) => {
                write!(f, "TooManyWebhooks")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

/** Response marker for the `place.stream.server.createWebhook` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `CreateWebhookOutput<S>` for this endpoint.*/
pub struct CreateWebhookResponse;
impl jacquard_common::xrpc::XrpcResp for CreateWebhookResponse {
    const NSID: &'static str = "place.stream.server.createWebhook";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = CreateWebhookOutput<S>;
    type Err = CreateWebhookError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for CreateWebhook<S> {
    const NSID: &'static str = "place.stream.server.createWebhook";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = CreateWebhookResponse;
}

/** Endpoint marker for the `place.stream.server.createWebhook` procedure.

Path: `/xrpc/place.stream.server.createWebhook`. The request payload type is `CreateWebhook<S>`; send that request with `jacquard::Client` or use this marker through lower-level `XrpcEndpoint` APIs.*/
pub struct CreateWebhookRequest;
impl jacquard_common::xrpc::XrpcEndpoint for CreateWebhookRequest {
    const PATH: &'static str = "/xrpc/place.stream.server.createWebhook";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Request<S: BosStr> = CreateWebhook<S>;
    type Response = CreateWebhookResponse;
}

fn _default_create_webhook_active() -> Option<bool> {
    Some(false)
}

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

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

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

impl<S: BosStr> CreateWebhook<S> {
    /// Create a new builder for this type
    pub fn builder() -> CreateWebhookBuilder<create_webhook_state::Empty, S> {
        CreateWebhookBuilder::builder()
    }
}

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

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

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

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

impl<St, S: BosStr> CreateWebhookBuilder<St, S>
where
    St: create_webhook_state::State,
    St::Events: create_webhook_state::IsUnset,
{
    /// Set the `events` field (required)
    pub fn events(
        mut self,
        value: impl Into<Vec<S>>,
    ) -> CreateWebhookBuilder<create_webhook_state::SetEvents<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CreateWebhookBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: create_webhook_state::State, S: BosStr> CreateWebhookBuilder<St, S> {
    /// Set the `muteWords` field (optional)
    pub fn mute_words(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `muteWords` field to an Option value (optional)
    pub fn maybe_mute_words(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: create_webhook_state::State, S: BosStr> CreateWebhookBuilder<St, S> {
    /// Set the `name` field (optional)
    pub fn name(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `name` field to an Option value (optional)
    pub fn maybe_name(mut self, value: Option<S>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St: create_webhook_state::State, S: BosStr> CreateWebhookBuilder<St, S> {
    /// Set the `prefix` field (optional)
    pub fn prefix(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.5 = value.into();
        self
    }
    /// Set the `prefix` field to an Option value (optional)
    pub fn maybe_prefix(mut self, value: Option<S>) -> Self {
        self._fields.5 = value;
        self
    }
}

impl<St: create_webhook_state::State, S: BosStr> CreateWebhookBuilder<St, S> {
    /// Set the `rewrite` field (optional)
    pub fn rewrite(mut self, value: impl Into<Option<Vec<RewriteRule<S>>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `rewrite` field to an Option value (optional)
    pub fn maybe_rewrite(mut self, value: Option<Vec<RewriteRule<S>>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: create_webhook_state::State, S: BosStr> CreateWebhookBuilder<St, S> {
    /// Set the `suffix` field (optional)
    pub fn suffix(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `suffix` field to an Option value (optional)
    pub fn maybe_suffix(mut self, value: Option<S>) -> Self {
        self._fields.7 = value;
        self
    }
}

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

impl<St, S: BosStr> CreateWebhookBuilder<St, S>
where
    St: create_webhook_state::State,
    St::Events: create_webhook_state::IsSet,
    St::Url: create_webhook_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CreateWebhook<S> {
        CreateWebhook {
            active: self._fields.0.or_else(|| Some(false)),
            description: self._fields.1,
            events: self._fields.2.unwrap(),
            mute_words: self._fields.3,
            name: self._fields.4,
            prefix: self._fields.5,
            rewrite: self._fields.6,
            suffix: self._fields.7,
            url: self._fields.8.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>>,
    ) -> CreateWebhook<S> {
        CreateWebhook {
            active: self._fields.0.or_else(|| Some(false)),
            description: self._fields.1,
            events: self._fields.2.unwrap(),
            mute_words: self._fields.3,
            name: self._fields.4,
            prefix: self._fields.5,
            rewrite: self._fields.6,
            suffix: self._fields.7,
            url: self._fields.8.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}