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

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::types::string::Datetime;
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, lexicon, 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};

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct DraftView<'a> {
    #[serde(borrow)]
    pub content: CowStr<'a>,
    pub created_at: Datetime,
    #[serde(borrow)]
    pub tid: CowStr<'a>,
    pub updated_at: Datetime,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase")]
pub struct PutDraft<'a> {
    ///Markdown content of the draft.
    #[serde(borrow)]
    pub content: CowStr<'a>,
    ///TID of an existing draft to update. Omit to create a new draft.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub tid: Option<CowStr<'a>>,
}


#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct PutDraftOutput<'a> {
    #[serde(flatten)]
    #[serde(borrow)]
    pub value: Data<'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 PutDraftError<'a> {
    #[serde(rename = "DraftNotFound")]
    DraftNotFound(Option<CowStr<'a>>),
}

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::Unknown(err) => write!(f, "Unknown error: {:?}", err),
        }
    }
}

impl<'a> LexiconSchema for DraftView<'a> {
    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 type for at.unthread.document.putDraft
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<'de> = PutDraftOutput<'de>;
    type Err<'de> = PutDraftError<'de>;
}

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

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

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

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

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

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

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

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

impl<'a, S> DraftViewBuilder<'a, S>
where
    S: draft_view_state::State,
    S::Tid: draft_view_state::IsSet,
    S::CreatedAt: draft_view_state::IsSet,
    S::UpdatedAt: draft_view_state::IsSet,
    S::Content: draft_view_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> DraftView<'a> {
        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<jacquard_common::deps::smol_str::SmolStr, Data<'a>>,
    ) -> DraftView<'a> {
        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()
    }
}