// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: place.stream.media.createUpload
//
// 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::{Datetime, UriValue};
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, open_union};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CreateUpload<S: BosStr = DefaultStr> {
    ///Optional filename hint to attach as upload metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<S>,
    ///MIME type of the content being uploaded (e.g. video/mp4).
    pub mime_type: S,
    ///Total size of the upload in bytes.
    pub size: i64,
    #[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 CreateUploadOutput<S: BosStr = DefaultStr> {
    ///When the upload token expires.
    pub expires_at: Datetime,
    ///Server-side identifier for this upload.
    pub upload_id: S,
    ///Short-lived bearer token bound to this upload. Send as 'Authorization: Bearer <token>' on TUS requests.
    pub upload_token: S,
    ///Absolute URL to PATCH/HEAD per the TUS protocol.
    pub upload_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,
    thiserror::Error,
    miette::Diagnostic
)]

#[serde(tag = "error", content = "message")]
pub enum CreateUploadError {
    /// The requested upload exceeds the server's maximum allowed size.
    #[serde(rename = "UploadTooLarge")]
    UploadTooLarge(Option<SmolStr>),
    /// The server does not accept this MIME type for upload.
    #[serde(rename = "UnsupportedMimeType")]
    UnsupportedMimeType(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for CreateUploadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::UploadTooLarge(msg) => {
                write!(f, "UploadTooLarge")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::UnsupportedMimeType(msg) => {
                write!(f, "UnsupportedMimeType")?;
                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.media.createUpload` procedure.

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

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

/** Endpoint marker for the `place.stream.media.createUpload` procedure.

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

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

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

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

impl<S: BosStr> CreateUpload<S> {
    /// Create a new builder for this type
    pub fn builder() -> CreateUploadBuilder<create_upload_state::Empty, S> {
        CreateUploadBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> CreateUploadBuilder<St, S>
where
    St: create_upload_state::State,
    St::MimeType: create_upload_state::IsUnset,
{
    /// Set the `mimeType` field (required)
    pub fn mime_type(
        mut self,
        value: impl Into<S>,
    ) -> CreateUploadBuilder<create_upload_state::SetMimeType<St>, S> {
        self._fields.1 = Option::Some(value.into());
        CreateUploadBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CreateUploadBuilder<St, S>
where
    St: create_upload_state::State,
    St::Size: create_upload_state::IsUnset,
{
    /// Set the `size` field (required)
    pub fn size(
        mut self,
        value: impl Into<i64>,
    ) -> CreateUploadBuilder<create_upload_state::SetSize<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CreateUploadBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CreateUploadBuilder<St, S>
where
    St: create_upload_state::State,
    St::MimeType: create_upload_state::IsSet,
    St::Size: create_upload_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> CreateUpload<S> {
        CreateUpload {
            filename: self._fields.0,
            mime_type: self._fields.1.unwrap(),
            size: self._fields.2.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>>,
    ) -> CreateUpload<S> {
        CreateUpload {
            filename: self._fields.0,
            mime_type: self._fields.1.unwrap(),
            size: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}