// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: at.unthread.document.putDraft
//
// 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::string::Datetime;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct DraftView<S: BosStr = DefaultStr> {
    pub content: S,
    pub created_at: Datetime,
    pub tid: S,
    pub updated_at: Datetime,
    #[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, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct PutDraft<S: BosStr = DefaultStr> {
    ///Markdown content of the draft.
    pub content: S,
    ///TID of an existing draft to update. Omit to create a new draft.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tid: Option<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 PutDraftOutput<S: BosStr = DefaultStr> {
    #[serde(flatten)]
    pub value: Data<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 PutDraftError {
    #[serde(rename = "DraftNotFound")]
    DraftNotFound(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for PutDraftError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::DraftNotFound(msg) => {
                write!(f, "DraftNotFound")?;
                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(())
            }
        }
    }
}

impl<S: BosStr> LexiconSchema for DraftView<S> {
    fn nsid() -> &'static str {
        "at.unthread.document.putDraft"
    }
    fn def_name() -> &'static str {
        "draftView"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_unthread_document_putDraft()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

/** Response marker for the `at.unthread.document.putDraft` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `PutDraftOutput<S>` for this endpoint.*/
pub struct PutDraftResponse;
impl jacquard_common::xrpc::XrpcResp for PutDraftResponse {
    const NSID: &'static str = "at.unthread.document.putDraft";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = PutDraftOutput<S>;
    type Err = PutDraftError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for PutDraft<S> {
    const NSID: &'static str = "at.unthread.document.putDraft";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = PutDraftResponse;
}

/** Endpoint marker for the `at.unthread.document.putDraft` procedure.

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

pub mod draft_view_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 Content;
        type CreatedAt;
        type Tid;
        type UpdatedAt;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Content = Unset;
        type CreatedAt = Unset;
        type Tid = Unset;
        type UpdatedAt = Unset;
    }
    ///State transition - sets the `content` field to Set
    pub struct SetContent<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetContent<St> {}
    impl<St: State> State for SetContent<St> {
        type Content = Set<members::content>;
        type CreatedAt = St::CreatedAt;
        type Tid = St::Tid;
        type UpdatedAt = St::UpdatedAt;
    }
    ///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 Content = St::Content;
        type CreatedAt = Set<members::created_at>;
        type Tid = St::Tid;
        type UpdatedAt = St::UpdatedAt;
    }
    ///State transition - sets the `tid` field to Set
    pub struct SetTid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTid<St> {}
    impl<St: State> State for SetTid<St> {
        type Content = St::Content;
        type CreatedAt = St::CreatedAt;
        type Tid = Set<members::tid>;
        type UpdatedAt = St::UpdatedAt;
    }
    ///State transition - sets the `updated_at` field to Set
    pub struct SetUpdatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetUpdatedAt<St> {}
    impl<St: State> State for SetUpdatedAt<St> {
        type Content = St::Content;
        type CreatedAt = St::CreatedAt;
        type Tid = St::Tid;
        type UpdatedAt = Set<members::updated_at>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `content` field
        pub struct content(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `tid` field
        pub struct tid(());
        ///Marker type for the `updated_at` field
        pub struct updated_at(());
    }
}

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

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

impl<S: BosStr> DraftView<S> {
    /// Create a new builder for this type
    pub fn builder() -> DraftViewBuilder<draft_view_state::Empty, S> {
        DraftViewBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> DraftViewBuilder<St, S>
where
    St: draft_view_state::State,
    St::Content: draft_view_state::IsUnset,
{
    /// Set the `content` field (required)
    pub fn content(
        mut self,
        value: impl Into<S>,
    ) -> DraftViewBuilder<draft_view_state::SetContent<St>, S> {
        self._fields.0 = Option::Some(value.into());
        DraftViewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St, S: BosStr> DraftViewBuilder<St, S>
where
    St: draft_view_state::State,
    St::Tid: draft_view_state::IsUnset,
{
    /// Set the `tid` field (required)
    pub fn tid(
        mut self,
        value: impl Into<S>,
    ) -> DraftViewBuilder<draft_view_state::SetTid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        DraftViewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DraftViewBuilder<St, S>
where
    St: draft_view_state::State,
    St::UpdatedAt: draft_view_state::IsUnset,
{
    /// Set the `updatedAt` field (required)
    pub fn updated_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> DraftViewBuilder<draft_view_state::SetUpdatedAt<St>, S> {
        self._fields.3 = Option::Some(value.into());
        DraftViewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DraftViewBuilder<St, S>
where
    St: draft_view_state::State,
    St::Content: draft_view_state::IsSet,
    St::CreatedAt: draft_view_state::IsSet,
    St::Tid: draft_view_state::IsSet,
    St::UpdatedAt: draft_view_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> DraftView<S> {
        DraftView {
            content: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            tid: self._fields.2.unwrap(),
            updated_at: self._fields.3.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>>,
    ) -> DraftView<S> {
        DraftView {
            content: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            tid: self._fields.2.unwrap(),
            updated_at: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_at_unthread_document_putDraft() -> 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("at.unthread.document.putDraft"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("draftView"),
                LexUserType::Object(LexObject {
                    required: Some(
                        vec![
                            SmolStr::new_static("tid"), SmolStr::new_static("content"),
                            SmolStr::new_static("createdAt"),
                            SmolStr::new_static("updatedAt")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("content"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("createdAt"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("tid"),
                            LexObjectProperty::String(LexString { ..Default::default() }),
                        );
                        map.insert(
                            SmolStr::new_static("updatedAt"),
                            LexObjectProperty::String(LexString {
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcProcedure(LexXrpcProcedure {
                    input: Some(LexXrpcBody {
                        encoding: CowStr::new_static("application/json"),
                        schema: Some(
                            LexXrpcBodySchema::Object(LexObject {
                                required: Some(vec![SmolStr::new_static("content")]),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("content"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("Markdown content of the draft."),
                                            ),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("tid"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "TID of an existing draft to update. Omit to create a new draft.",
                                                ),
                                            ),
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}