// Copyright 2024, 2025 New Vector Ltd.
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.

use std::time::Duration;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use url::Url;

use crate::ConfigurationSection;

const fn default_true() -> bool {
    true
}

#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_default_true(value: &bool) -> bool {
    *value == default_true()
}

const fn default_false() -> bool {
    false
}

#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_default_false(value: &bool) -> bool {
    *value == default_false()
}

fn default_postnumber_timeout() -> Duration {
    Duration::from_secs(2)
}

fn is_default_postnumber_timeout(value: &Duration) -> bool {
    *value == default_postnumber_timeout()
}

/// How MAS should behave when the postnumber resolver cannot be reached.
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PostnumberValidationFailureMode {
    /// Allow the registration or admin action to proceed without resolver
    /// input.
    Open,
    /// Reject the registration or admin action when the resolver is
    /// unavailable.
    Closed,
}

impl Default for PostnumberValidationFailureMode {
    fn default() -> Self {
        Self::Closed
    }
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
/// Configuration for the external postnumber resolver integration.
pub struct PostnumberValidationConfig {
    /// Resolver endpoint used to validate user-facing postnumbers.
    pub endpoint: Url,

    /// Per-request timeout when calling the resolver.
    #[serde_as(as = "serde_with::DurationSeconds<u64>")]
    #[schemars(with = "u64")]
    #[serde(
        default = "default_postnumber_timeout",
        skip_serializing_if = "is_default_postnumber_timeout"
    )]
    pub timeout: Duration,

    /// Behavior when the resolver cannot be reached or returns an unexpected
    /// error.
    #[serde(default)]
    pub on_unavailable: PostnumberValidationFailureMode,
}

/// Configuration section to configure features related to account management
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
pub struct AccountConfig {
    /// Whether users are allowed to change their email addresses. Defaults to
    /// `true`.
    #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
    pub email_change_allowed: bool,

    /// Whether users are allowed to change their display names. Defaults to
    /// `true`.
    ///
    /// This should be in sync with the policy in the homeserver configuration.
    #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
    pub displayname_change_allowed: bool,

    /// Whether to enable self-service password registration. Defaults to
    /// `false` if password authentication is enabled.
    ///
    /// This has no effect if password login is disabled.
    #[serde(default = "default_false", skip_serializing_if = "is_default_false")]
    pub password_registration_enabled: bool,

    /// Whether self-service password registrations require a valid email.
    /// Defaults to `true`.
    ///
    /// This has no effect if password registration is disabled.
    #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
    pub password_registration_email_required: bool,

    /// Whether users are allowed to change their passwords. Defaults to `true`.
    ///
    /// This has no effect if password login is disabled.
    #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
    pub password_change_allowed: bool,

    /// Whether email-based password recovery is enabled. Defaults to `false`.
    ///
    /// This has no effect if password login is disabled.
    #[serde(default = "default_false", skip_serializing_if = "is_default_false")]
    pub password_recovery_enabled: bool,

    /// Whether users are allowed to delete their own account. Defaults to
    /// `true`.
    #[serde(default = "default_true", skip_serializing_if = "is_default_true")]
    pub account_deactivation_allowed: bool,

    /// Whether users can log in with their email address. Defaults to `false`.
    ///
    /// This has no effect if password login is disabled.
    #[serde(default = "default_false", skip_serializing_if = "is_default_false")]
    pub login_with_email_allowed: bool,

    /// Whether registration tokens are required for password registrations.
    /// Defaults to `false`.
    ///
    /// When enabled, users must provide a valid registration token during
    /// password registration. This has no effect if password registration
    /// is disabled.
    #[serde(default = "default_false", skip_serializing_if = "is_default_false")]
    pub registration_token_required: bool,

    /// Optional external resolver for validating user-facing postnumbers in
    /// registration flows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub postnumber_validation: Option<PostnumberValidationConfig>,
}

impl Default for AccountConfig {
    fn default() -> Self {
        Self {
            email_change_allowed: default_true(),
            displayname_change_allowed: default_true(),
            password_registration_enabled: default_false(),
            password_registration_email_required: default_true(),
            password_change_allowed: default_true(),
            password_recovery_enabled: default_false(),
            account_deactivation_allowed: default_true(),
            login_with_email_allowed: default_false(),
            registration_token_required: default_false(),
            postnumber_validation: None,
        }
    }
}

impl AccountConfig {
    /// Returns true if the configuration is the default one
    pub(crate) fn is_default(&self) -> bool {
        is_default_false(&self.password_registration_enabled)
            && is_default_true(&self.email_change_allowed)
            && is_default_true(&self.displayname_change_allowed)
            && is_default_true(&self.password_change_allowed)
            && is_default_false(&self.password_recovery_enabled)
            && is_default_true(&self.account_deactivation_allowed)
            && is_default_false(&self.login_with_email_allowed)
            && is_default_false(&self.registration_token_required)
            && self.postnumber_validation.is_none()
    }
}

impl ConfigurationSection for AccountConfig {
    const PATH: Option<&'static str> = Some("account");
}
