// @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;

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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.

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Webhook<'a> {
    ///RFC3339 timestamp of when the webhook was created
    pub created_at: Datetime,
    ///DID of the hold where the webhook is configured
    #[serde(borrow)]
    pub hold_did: Did<'a>,
    ///CID of the corresponding io.atcr.hold.webhook record on the hold
    #[serde(borrow)]
    pub private_cid: CowStr<'a>,
    ///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>,
}

/// 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<'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: Webhook<'a>,
}

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

/// 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<'de> = WebhookGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

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

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

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

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

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

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

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

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

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

impl<'a, S: webhook_state::State> WebhookBuilder<'a, 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<'a, S> WebhookBuilder<'a, S>
where
    S: webhook_state::State,
    S::HoldDid: webhook_state::IsSet,
    S::PrivateCid: webhook_state::IsSet,
    S::CreatedAt: webhook_state::IsSet,
    S::Triggers: webhook_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Webhook<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Webhook<'a> {
        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()
    }
}