// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.atcr.sailor.webhook
//
// 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::{Did, 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};
/// Public webhook metadata stored in the user's PDS. Links to a private io.atcr.hold.webhook record on the hold where URL and secret are stored. Part of a two-record split: this record is visible via ATProto (Jetstream), the hold record is not.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "io.atcr.sailor.webhook",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Webhook<S: BosStr = DefaultStr> {
    ///RFC3339 timestamp of when the webhook was created
    pub created_at: Datetime,
    ///DID of the hold where the webhook is configured
    pub hold_did: Did<S>,
    ///CID of the corresponding io.atcr.hold.webhook record on the hold
    pub private_cid: S,
    ///Bitmask of trigger events: 0x01=scan:first, 0x02=scan:all, 0x04=scan:changed
    pub triggers: i64,
    ///RFC3339 timestamp of when the webhook was last updated
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    #[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 WebhookGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Webhook<S>,
}

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

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

#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookRecord;
impl XrpcResp for WebhookRecord {
    const NSID: &'static str = "io.atcr.sailor.webhook";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = WebhookGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Webhook<S> {
    const NSID: &'static str = "io.atcr.sailor.webhook";
    type Record = WebhookRecord;
}

impl Collection for WebhookRecord {
    const NSID: &'static str = "io.atcr.sailor.webhook";
    type Record = WebhookRecord;
}

impl<S: BosStr> LexiconSchema for Webhook<S> {
    fn nsid() -> &'static str {
        "io.atcr.sailor.webhook"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_io_atcr_sailor_webhook()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.private_cid;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("private_cid"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.triggers;
            if *value < 0i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("triggers"),
                    min: 0i64,
                    actual: *value,
                });
            }
        }
        Ok(())
    }
}

pub mod 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 CreatedAt;
        type HoldDid;
        type PrivateCid;
        type Triggers;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type CreatedAt = Unset;
        type HoldDid = Unset;
        type PrivateCid = Unset;
        type Triggers = Unset;
    }
    ///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 CreatedAt = Set<members::created_at>;
        type HoldDid = St::HoldDid;
        type PrivateCid = St::PrivateCid;
        type Triggers = St::Triggers;
    }
    ///State transition - sets the `hold_did` field to Set
    pub struct SetHoldDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetHoldDid<St> {}
    impl<St: State> State for SetHoldDid<St> {
        type CreatedAt = St::CreatedAt;
        type HoldDid = Set<members::hold_did>;
        type PrivateCid = St::PrivateCid;
        type Triggers = St::Triggers;
    }
    ///State transition - sets the `private_cid` field to Set
    pub struct SetPrivateCid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetPrivateCid<St> {}
    impl<St: State> State for SetPrivateCid<St> {
        type CreatedAt = St::CreatedAt;
        type HoldDid = St::HoldDid;
        type PrivateCid = Set<members::private_cid>;
        type Triggers = St::Triggers;
    }
    ///State transition - sets the `triggers` field to Set
    pub struct SetTriggers<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTriggers<St> {}
    impl<St: State> State for SetTriggers<St> {
        type CreatedAt = St::CreatedAt;
        type HoldDid = St::HoldDid;
        type PrivateCid = St::PrivateCid;
        type Triggers = Set<members::triggers>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `hold_did` field
        pub struct hold_did(());
        ///Marker type for the `private_cid` field
        pub struct private_cid(());
        ///Marker type for the `triggers` field
        pub struct triggers(());
    }
}

/// Builder for constructing an instance of this type.
pub struct WebhookBuilder<St: webhook_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Datetime>,
        Option<Did<S>>,
        Option<S>,
        Option<i64>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Webhook<S> {
    /// Create a new builder for this type
    pub fn builder() -> WebhookBuilder<webhook_state::Empty, S> {
        WebhookBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> WebhookBuilder<St, S>
where
    St: webhook_state::State,
    St::HoldDid: webhook_state::IsUnset,
{
    /// Set the `holdDid` field (required)
    pub fn hold_did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> WebhookBuilder<webhook_state::SetHoldDid<St>, S> {
        self._fields.1 = Option::Some(value.into());
        WebhookBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> WebhookBuilder<St, S>
where
    St: webhook_state::State,
    St::PrivateCid: webhook_state::IsUnset,
{
    /// Set the `privateCid` field (required)
    pub fn private_cid(
        mut self,
        value: impl Into<S>,
    ) -> WebhookBuilder<webhook_state::SetPrivateCid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        WebhookBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> WebhookBuilder<St, S>
where
    St: webhook_state::State,
    St::Triggers: webhook_state::IsUnset,
{
    /// Set the `triggers` field (required)
    pub fn triggers(
        mut self,
        value: impl Into<i64>,
    ) -> WebhookBuilder<webhook_state::SetTriggers<St>, S> {
        self._fields.3 = Option::Some(value.into());
        WebhookBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: webhook_state::State, S: BosStr> WebhookBuilder<St, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `updatedAt` field to an Option value (optional)
    pub fn maybe_updated_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> WebhookBuilder<St, S>
where
    St: webhook_state::State,
    St::CreatedAt: webhook_state::IsSet,
    St::HoldDid: webhook_state::IsSet,
    St::PrivateCid: webhook_state::IsSet,
    St::Triggers: webhook_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Webhook<S> {
        Webhook {
            created_at: self._fields.0.unwrap(),
            hold_did: self._fields.1.unwrap(),
            private_cid: self._fields.2.unwrap(),
            triggers: self._fields.3.unwrap(),
            updated_at: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Webhook<S> {
        Webhook {
            created_at: self._fields.0.unwrap(),
            hold_did: self._fields.1.unwrap(),
            private_cid: self._fields.2.unwrap(),
            triggers: self._fields.3.unwrap(),
            updated_at: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_io_atcr_sailor_webhook() -> 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("io.atcr.sailor.webhook"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Public webhook metadata stored in the user's PDS. Links to a private io.atcr.hold.webhook record on the hold where URL and secret are stored. Part of a two-record split: this record is visible via ATProto (Jetstream), the hold record is not.",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("holdDid"),
                                SmolStr::new_static("triggers"),
                                SmolStr::new_static("privateCid"),
                                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(
                                            "RFC3339 timestamp of when the webhook was created",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("holdDid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "DID of the hold where the webhook is configured",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Did),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("privateCid"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "CID of the corresponding io.atcr.hold.webhook record on the hold",
                                        ),
                                    ),
                                    max_length: Some(128usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("triggers"),
                                LexObjectProperty::Integer(LexInteger {
                                    minimum: Some(0i64),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "RFC3339 timestamp of when the webhook was last updated",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}