// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: org.atsui.List
//
// 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::{Did, Nsid};
use jacquard_common::types::value::Data;
use jacquard_derive::IntoStatic;
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

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

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct List<S: BosStr = DefaultStr> {
    ///DID of the service that implements the query.
    pub did: Did<S>,
    ///Parameters to pass to the query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<Data<S>>,
    ///XRPC query to call for pages of items.
    pub query: Nsid<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 ListOutput<S: BosStr = DefaultStr> {
    #[serde(flatten)]
    pub value: Response<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Response shape from a List data source query.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Page<S: BosStr = DefaultStr> {
    ///Opaque pagination token. Absent means no more items.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<S>,
    ///Elements to render as list rows.
    pub items: Vec<Element<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/** Response marker for the `org.atsui.List` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `ListOutput<S>` for this endpoint.*/
pub struct ListResponse;
impl jacquard_common::xrpc::XrpcResp for ListResponse {
    const NSID: &'static str = "org.atsui.List";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ListOutput<S>;
    type Err = jacquard_common::xrpc::GenericError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for List<S> {
    const NSID: &'static str = "org.atsui.List";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = ListResponse;
}

/** Endpoint marker for the `org.atsui.List` procedure.

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

impl<S: BosStr> LexiconSchema for Page<S> {
    fn nsid() -> &'static str {
        "org.atsui.List"
    }
    fn def_name() -> &'static str {
        "page"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_org_atsui_List()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.cursor {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("cursor"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod list_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 Did;
        type Query;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Did = Unset;
        type Query = Unset;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDid<St> {}
    impl<St: State> State for SetDid<St> {
        type Did = Set<members::did>;
        type Query = St::Query;
    }
    ///State transition - sets the `query` field to Set
    pub struct SetQuery<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetQuery<St> {}
    impl<St: State> State for SetQuery<St> {
        type Did = St::Did;
        type Query = Set<members::query>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `did` field
        pub struct did(());
        ///Marker type for the `query` field
        pub struct query(());
    }
}

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

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

impl<S: BosStr> List<S> {
    /// Create a new builder for this type
    pub fn builder() -> ListBuilder<list_state::Empty, S> {
        ListBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ListBuilder<St, S>
where
    St: list_state::State,
    St::Did: list_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> ListBuilder<list_state::SetDid<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ListBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: list_state::State, S: BosStr> ListBuilder<St, S> {
    /// Set the `input` field (optional)
    pub fn input(mut self, value: impl Into<Option<Data<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `input` field to an Option value (optional)
    pub fn maybe_input(mut self, value: Option<Data<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> ListBuilder<St, S>
where
    St: list_state::State,
    St::Query: list_state::IsUnset,
{
    /// Set the `query` field (required)
    pub fn query(
        mut self,
        value: impl Into<Nsid<S>>,
    ) -> ListBuilder<list_state::SetQuery<St>, S> {
        self._fields.2 = Option::Some(value.into());
        ListBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ListBuilder<St, S>
where
    St: list_state::State,
    St::Did: list_state::IsSet,
    St::Query: list_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> List<S> {
        List {
            did: self._fields.0.unwrap(),
            input: self._fields.1,
            query: 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>>) -> List<S> {
        List {
            did: self._fields.0.unwrap(),
            input: self._fields.1,
            query: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

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

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

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

impl<S: BosStr> Page<S> {
    /// Create a new builder for this type
    pub fn builder() -> PageBuilder<page_state::Empty, S> {
        PageBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> PageBuilder<St, S>
where
    St: page_state::State,
    St::Items: page_state::IsUnset,
{
    /// Set the `items` field (required)
    pub fn items(
        mut self,
        value: impl Into<Vec<Element<S>>>,
    ) -> PageBuilder<page_state::SetItems<St>, S> {
        self._fields.1 = Option::Some(value.into());
        PageBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> PageBuilder<St, S>
where
    St: page_state::State,
    St::Items: page_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Page<S> {
        Page {
            cursor: self._fields.0,
            items: self._fields.1.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>>) -> Page<S> {
        Page {
            cursor: self._fields.0,
            items: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_org_atsui_List() -> 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("org.atsui.List"),
        defs: {
            let mut map = BTreeMap::new();
            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("query"), SmolStr::new_static("did")
                                    ],
                                ),
                                properties: {
                                    #[allow(unused_mut)]
                                    let mut map = BTreeMap::new();
                                    map.insert(
                                        SmolStr::new_static("did"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static(
                                                    "DID of the service that implements the query.",
                                                ),
                                            ),
                                            format: Some(LexStringFormat::Did),
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("input"),
                                        LexObjectProperty::Unknown(LexUnknown {
                                            ..Default::default()
                                        }),
                                    );
                                    map.insert(
                                        SmolStr::new_static("query"),
                                        LexObjectProperty::String(LexString {
                                            description: Some(
                                                CowStr::new_static("XRPC query to call for pages of items."),
                                            ),
                                            format: Some(LexStringFormat::Nsid),
                                            ..Default::default()
                                        }),
                                    );
                                    map
                                },
                                ..Default::default()
                            }),
                        ),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("page"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Response shape from a List data source query.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("items")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("cursor"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Opaque pagination token. Absent means no more items.",
                                    ),
                                ),
                                max_length: Some(512usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("items"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("Elements to render as list rows."),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("at.inlay.defs#element"),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}