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

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
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::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

#[lexicon]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct Report<'a> {
    ///AT URI of the beacon being reported
    #[serde(borrow)]
    pub beacon_uri: AtUri<'a>,
    ///Timestamp when the report was created
    pub created_at: Datetime,
    ///Additional context for the report
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub details: Option<CowStr<'a>>,
    ///Reason for the report
    #[serde(borrow)]
    pub reason: ReportReason<'a>,
}

/// Reason for the report

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ReportReason<'a> {
    Spam,
    InappropriateContent,
    Doxxing,
    Harassment,
    Impersonation,
    Other,
    UnknownValue(CowStr<'a>),
}

impl<'a> ReportReason<'a> {
    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(),
        }
    }
}

impl<'a> From<&'a str> for ReportReason<'a> {
    fn from(s: &'a str) -> Self {
        match s {
            "spam" => Self::Spam,
            "inappropriate_content" => Self::InappropriateContent,
            "doxxing" => Self::Doxxing,
            "harassment" => Self::Harassment,
            "impersonation" => Self::Impersonation,
            "other" => Self::Other,
            _ => Self::UnknownValue(CowStr::from(s)),
        }
    }
}

impl<'a> From<String> for ReportReason<'a> {
    fn from(s: String) -> Self {
        match s.as_str() {
            "spam" => Self::Spam,
            "inappropriate_content" => Self::InappropriateContent,
            "doxxing" => Self::Doxxing,
            "harassment" => Self::Harassment,
            "impersonation" => Self::Impersonation,
            "other" => Self::Other,
            _ => Self::UnknownValue(CowStr::from(s)),
        }
    }
}

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

impl<'a> AsRef<str> for ReportReason<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

impl<'de, 'a> serde::Deserialize<'de> for ReportReason<'a>
where
    'de: 'a,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = <&'de str>::deserialize(deserializer)?;
        Ok(Self::from(s))
    }
}

impl<'a> Default for ReportReason<'a> {
    fn default() -> Self {
        Self::UnknownValue(Default::default())
    }
}

impl jacquard_common::IntoStatic for ReportReason<'_> {
    type Output = ReportReason<'static>;
    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<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub cid: Option<Cid<'a>>,
    #[serde(borrow)]
    pub uri: AtUri<'a>,
    #[serde(borrow)]
    pub value: Report<'a>,
}

impl<'a> Report<'a> {
    pub fn uri(
        uri: impl Into<CowStr<'a>>,
    ) -> Result<RecordUri<'a, ReportRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
    }
}

/// 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<'de> = ReportGetRecordOutput<'de>;
    type Err<'de> = RecordError<'de>;
}

impl From<ReportGetRecordOutput<'_>> for Report<'_> {
    fn from(output: ReportGetRecordOutput<'_>) -> Self {
        use jacquard_common::IntoStatic;
        output.value.into_static()
    }
}

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

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

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

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

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

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

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

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

impl<'a, S> ReportBuilder<'a, S>
where
    S: report_state::State,
    S::Reason: report_state::IsSet,
    S::CreatedAt: report_state::IsSet,
    S::BeaconUri: report_state::IsSet,
{
    /// Build the final struct
    pub fn build(self) -> Report<'a> {
        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<
            jacquard_common::deps::smol_str::SmolStr,
            jacquard_common::types::value::Data<'a>,
        >,
    ) -> Report<'a> {
        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()
    }
}