// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: app.beaconbits.report
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
/// A report of inappropriate content on a beacon

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "app.beaconbits.report",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Report<S: BosStr = DefaultStr> {
    ///AT URI of the beacon being reported
    pub beacon_uri: AtUri<S>,
    ///Timestamp when the report was created
    pub created_at: Datetime,
    ///Additional context for the report
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<S>,
    ///Reason for the report
    pub reason: ReportReason<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Reason for the report

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ReportReason<S: BosStr = DefaultStr> {
    Spam,
    InappropriateContent,
    Doxxing,
    Harassment,
    Impersonation,
    Other,
    UnknownValue(S),
}

impl<S: BosStr> ReportReason<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Spam => "spam",
            Self::InappropriateContent => "inappropriate_content",
            Self::Doxxing => "doxxing",
            Self::Harassment => "harassment",
            Self::Impersonation => "impersonation",
            Self::Other => "other",
            Self::UnknownValue(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "spam" => Self::Spam,
            "inappropriate_content" => Self::InappropriateContent,
            "doxxing" => Self::Doxxing,
            "harassment" => Self::Harassment,
            "impersonation" => Self::Impersonation,
            "other" => Self::Other,
            _ => Self::UnknownValue(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for ReportReason<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for ReportReason<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for ReportReason<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for ReportReason<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for ReportReason<S> {
    fn default() -> Self {
        Self::UnknownValue(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for ReportReason<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = ReportReason<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            ReportReason::Spam => ReportReason::Spam,
            ReportReason::InappropriateContent => ReportReason::InappropriateContent,
            ReportReason::Doxxing => ReportReason::Doxxing,
            ReportReason::Harassment => ReportReason::Harassment,
            ReportReason::Impersonation => ReportReason::Impersonation,
            ReportReason::Other => ReportReason::Other,
            ReportReason::UnknownValue(v) => ReportReason::UnknownValue(v.into_static()),
        }
    }
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct ReportGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Report<S>,
}

impl<S: BosStr> Report<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, ReportRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct ReportRecord;
impl XrpcResp for ReportRecord {
    const NSID: &'static str = "app.beaconbits.report";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ReportGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<ReportGetRecordOutput<S>> for Report<S> {
    fn from(output: ReportGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Report<S> {
    const NSID: &'static str = "app.beaconbits.report";
    type Record = ReportRecord;
}

impl Collection for ReportRecord {
    const NSID: &'static str = "app.beaconbits.report";
    type Record = ReportRecord;
}

impl<S: BosStr> LexiconSchema for Report<S> {
    fn nsid() -> &'static str {
        "app.beaconbits.report"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_app_beaconbits_report()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.details {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 500usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("details"),
                        max: 500usize,
                        actual: count,
                    });
                }
            }
        }
        {
            let value = &self.reason;
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 64usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("reason"),
                        max: 64usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

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

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

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

impl<S: BosStr> Report<S> {
    /// Create a new builder for this type
    pub fn builder() -> ReportBuilder<report_state::Empty, S> {
        ReportBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ReportBuilder<St, S>
where
    St: report_state::State,
    St::BeaconUri: report_state::IsUnset,
{
    /// Set the `beaconUri` field (required)
    pub fn beacon_uri(
        mut self,
        value: impl Into<AtUri<S>>,
    ) -> ReportBuilder<report_state::SetBeaconUri<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ReportBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

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

impl<St: report_state::State, S: BosStr> ReportBuilder<St, S> {
    /// Set the `details` field (optional)
    pub fn details(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `details` field to an Option value (optional)
    pub fn maybe_details(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St, S: BosStr> ReportBuilder<St, S>
where
    St: report_state::State,
    St::Reason: report_state::IsUnset,
{
    /// Set the `reason` field (required)
    pub fn reason(
        mut self,
        value: impl Into<ReportReason<S>>,
    ) -> ReportBuilder<report_state::SetReason<St>, S> {
        self._fields.3 = Option::Some(value.into());
        ReportBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ReportBuilder<St, S>
where
    St: report_state::State,
    St::BeaconUri: report_state::IsSet,
    St::CreatedAt: report_state::IsSet,
    St::Reason: report_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Report<S> {
        Report {
            beacon_uri: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            details: self._fields.2,
            reason: 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>>) -> Report<S> {
        Report {
            beacon_uri: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            details: self._fields.2,
            reason: self._fields.3.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_app_beaconbits_report() -> 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("app.beaconbits.report"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "A report of inappropriate content on a beacon",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("beaconUri"),
                                SmolStr::new_static("reason"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("beaconUri"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("AT URI of the beacon being reported"),
                                    ),
                                    format: Some(LexStringFormat::AtUri),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Timestamp when the report was created"),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("details"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Additional context for the report"),
                                    ),
                                    max_graphemes: Some(500usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("reason"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static("Reason for the report"),
                                    ),
                                    max_graphemes: Some(64usize),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}