// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: io.atcr.hold.setStats
//
// 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::{Did, Datetime};
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 SetStats<S: BosStr = DefaultStr> {
    ///RFC3339 timestamp of last pull
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_pull: Option<Datetime>,
    ///RFC3339 timestamp of last push
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_push: Option<Datetime>,
    ///DID of the repository owner
    pub owner_did: Did<S>,
    ///Absolute pull count to set
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pull_count: Option<i64>,
    ///Absolute push count to set
    #[serde(skip_serializing_if = "Option::is_none")]
    pub push_count: Option<i64>,
    ///Repository name
    pub repository: 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 SetStatsOutput<S: BosStr = DefaultStr> {
    ///Whether the stats were successfully updated
    pub success: bool,
    #[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 SetStatsError {
    #[serde(rename = "InvalidOwner")]
    InvalidOwner(Option<SmolStr>),
    #[serde(rename = "InvalidRepository")]
    InvalidRepository(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for SetStatsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidOwner(msg) => {
                write!(f, "InvalidOwner")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::InvalidRepository(msg) => {
                write!(f, "InvalidRepository")?;
                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 `io.atcr.hold.setStats` procedure.

Implements `jacquard_common::xrpc::XrpcResp`; successful bodies decode as `Self::Output<S>`, which is `SetStatsOutput<S>` for this endpoint.*/
pub struct SetStatsResponse;
impl jacquard_common::xrpc::XrpcResp for SetStatsResponse {
    const NSID: &'static str = "io.atcr.hold.setStats";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = SetStatsOutput<S>;
    type Err = SetStatsError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcRequest for SetStats<S> {
    const NSID: &'static str = "io.atcr.hold.setStats";
    const METHOD: jacquard_common::xrpc::XrpcMethod = jacquard_common::xrpc::XrpcMethod::Procedure(
        "application/json",
    );
    type Response = SetStatsResponse;
}

/** Endpoint marker for the `io.atcr.hold.setStats` procedure.

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

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

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

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

impl<S: BosStr> SetStats<S> {
    /// Create a new builder for this type
    pub fn builder() -> SetStatsBuilder<set_stats_state::Empty, S> {
        SetStatsBuilder::builder()
    }
}

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

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

impl<St: set_stats_state::State, S: BosStr> SetStatsBuilder<St, S> {
    /// Set the `lastPull` field (optional)
    pub fn last_pull(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `lastPull` field to an Option value (optional)
    pub fn maybe_last_pull(mut self, value: Option<Datetime>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St: set_stats_state::State, S: BosStr> SetStatsBuilder<St, S> {
    /// Set the `lastPush` field (optional)
    pub fn last_push(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `lastPush` field to an Option value (optional)
    pub fn maybe_last_push(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St, S: BosStr> SetStatsBuilder<St, S>
where
    St: set_stats_state::State,
    St::OwnerDid: set_stats_state::IsUnset,
{
    /// Set the `ownerDid` field (required)
    pub fn owner_did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> SetStatsBuilder<set_stats_state::SetOwnerDid<St>, S> {
        self._fields.2 = Option::Some(value.into());
        SetStatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: set_stats_state::State, S: BosStr> SetStatsBuilder<St, S> {
    /// Set the `pullCount` field (optional)
    pub fn pull_count(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `pullCount` field to an Option value (optional)
    pub fn maybe_pull_count(mut self, value: Option<i64>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St: set_stats_state::State, S: BosStr> SetStatsBuilder<St, S> {
    /// Set the `pushCount` field (optional)
    pub fn push_count(mut self, value: impl Into<Option<i64>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `pushCount` field to an Option value (optional)
    pub fn maybe_push_count(mut self, value: Option<i64>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> SetStatsBuilder<St, S>
where
    St: set_stats_state::State,
    St::Repository: set_stats_state::IsUnset,
{
    /// Set the `repository` field (required)
    pub fn repository(
        mut self,
        value: impl Into<S>,
    ) -> SetStatsBuilder<set_stats_state::SetRepository<St>, S> {
        self._fields.5 = Option::Some(value.into());
        SetStatsBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> SetStatsBuilder<St, S>
where
    St: set_stats_state::State,
    St::OwnerDid: set_stats_state::IsSet,
    St::Repository: set_stats_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> SetStats<S> {
        SetStats {
            last_pull: self._fields.0,
            last_push: self._fields.1,
            owner_did: self._fields.2.unwrap(),
            pull_count: self._fields.3,
            push_count: self._fields.4,
            repository: self._fields.5.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>>) -> SetStats<S> {
        SetStats {
            last_pull: self._fields.0,
            last_push: self._fields.1,
            owner_did: self._fields.2.unwrap(),
            pull_count: self._fields.3,
            push_count: self._fields.4,
            repository: self._fields.5.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}