// Copyright 2024, 2025 New Vector Ltd.
// Copyright 2022-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 anyhow::bail;
use camino::Utf8PathBuf;
use rand::Rng;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

mod account;
mod branding;
mod captcha;
mod clients;
mod database;
mod email;
mod experimental;
mod http;
mod matrix;
mod oauth;
mod passwords;
mod policy;
mod rate_limiting;
mod secrets;
mod telemetry;
mod templates;
mod upstream_oauth2;

pub use self::{
    account::AccountConfig,
    branding::BrandingConfig,
    captcha::{CaptchaConfig, CaptchaServiceKind},
    clients::{ClientAuthMethodConfig, ClientConfig, ClientsConfig},
    database::{DatabaseConfig, PgSslMode},
    email::{EmailConfig, EmailSmtpMode, EmailTransportKind},
    experimental::{ExperimentalConfig, SessionLimitConfig as ExperimentalSessionLimitConfig},
    http::{
        BindConfig as HttpBindConfig, HttpConfig, ListenerConfig as HttpListenerConfig,
        Resource as HttpResource, TlsConfig as HttpTlsConfig, UnixOrTcp,
    },
    matrix::{HomeserverKind, MatrixConfig},
    oauth::OAuthConfig,
    passwords::{
        Algorithm as PasswordAlgorithm, HashingScheme as PasswordHashingScheme, PasswordsConfig,
    },
    policy::PolicyConfig,
    rate_limiting::RateLimitingConfig,
    secrets::SecretsConfig,
    telemetry::{
        MetricsConfig, MetricsExporterKind, Propagator, TelemetryConfig, TracingConfig,
        TracingExporterKind,
    },
    templates::TemplatesConfig,
    upstream_oauth2::{
        ClaimsImports as UpstreamOAuth2ClaimsImports, DiscoveryMode as UpstreamOAuth2DiscoveryMode,
        EmailImportPreference as UpstreamOAuth2EmailImportPreference,
        ImportAction as UpstreamOAuth2ImportAction,
        OnBackchannelLogout as UpstreamOAuth2OnBackchannelLogout,
        OnConflict as UpstreamOAuth2OnConflict, PkceMethod as UpstreamOAuth2PkceMethod,
        Provider as UpstreamOAuth2Provider, ResponseMode as UpstreamOAuth2ResponseMode,
        TokenAuthMethod as UpstreamOAuth2TokenAuthMethod, UpstreamOAuth2Config,
    },
};
use crate::util::ConfigurationSection;

/// Application configuration root
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct RootConfig {
    /// List of OAuth 2.0/OIDC clients config
    #[serde(default, skip_serializing_if = "ClientsConfig::is_default")]
    pub clients: ClientsConfig,

    /// Configuration of the HTTP server
    #[serde(default)]
    pub http: HttpConfig,

    /// Database connection configuration
    #[serde(default)]
    pub database: DatabaseConfig,

    /// Configuration related to sending monitoring data
    #[serde(default, skip_serializing_if = "TelemetryConfig::is_default")]
    pub telemetry: TelemetryConfig,

    /// Configuration related to templates
    #[serde(default, skip_serializing_if = "TemplatesConfig::is_default")]
    pub templates: TemplatesConfig,

    /// Configuration related to sending emails
    #[serde(default)]
    pub email: EmailConfig,

    /// Application secrets
    pub secrets: SecretsConfig,

    /// Configuration related to user passwords
    #[serde(default)]
    pub passwords: PasswordsConfig,

    /// Configuration related to the homeserver
    pub matrix: MatrixConfig,

    /// Configuration related to the OPA policies
    #[serde(default, skip_serializing_if = "PolicyConfig::is_default")]
    pub policy: PolicyConfig,

    /// Configuration related to limiting the rate of user actions to prevent
    /// abuse
    #[serde(default, skip_serializing_if = "RateLimitingConfig::is_default")]
    pub rate_limiting: RateLimitingConfig,

    /// Configuration related to upstream OAuth providers
    #[serde(default, skip_serializing_if = "UpstreamOAuth2Config::is_default")]
    pub upstream_oauth2: UpstreamOAuth2Config,

    /// Configuration section for tweaking the branding of the service
    #[serde(default, skip_serializing_if = "BrandingConfig::is_default")]
    pub branding: BrandingConfig,

    /// Configuration section to setup CAPTCHA protection on a few operations
    #[serde(default, skip_serializing_if = "CaptchaConfig::is_default")]
    pub captcha: CaptchaConfig,

    /// Configuration section to configure features related to account
    /// management
    #[serde(default, skip_serializing_if = "AccountConfig::is_default")]
    pub account: AccountConfig,

    /// Configuration section for OAuth 2.0 protocol options
    #[serde(default, skip_serializing_if = "OAuthConfig::is_default")]
    pub oauth: OAuthConfig,

    /// Experimental configuration options
    #[serde(default, skip_serializing_if = "ExperimentalConfig::is_default")]
    pub experimental: ExperimentalConfig,
}

impl ConfigurationSection for RootConfig {
    fn validate(
        &self,
        figment: &figment::Figment,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
        self.clients.validate(figment)?;
        self.http.validate(figment)?;
        self.database.validate(figment)?;
        self.telemetry.validate(figment)?;
        self.templates.validate(figment)?;
        self.email.validate(figment)?;
        self.passwords.validate(figment)?;
        self.secrets.validate(figment)?;
        self.matrix.validate(figment)?;
        self.policy.validate(figment)?;
        self.rate_limiting.validate(figment)?;
        self.upstream_oauth2.validate(figment)?;
        self.branding.validate(figment)?;
        self.captcha.validate(figment)?;
        self.account.validate(figment)?;
        self.oauth.validate(figment)?;
        self.experimental.validate(figment)?;

        Ok(())
    }
}

impl RootConfig {
    /// Generate a new configuration with random secrets
    ///
    /// # Errors
    ///
    /// Returns an error if the secrets could not be generated
    pub async fn generate<R>(mut rng: R) -> anyhow::Result<Self>
    where
        R: Rng + Send,
    {
        Ok(Self {
            clients: ClientsConfig::default(),
            http: HttpConfig::default(),
            database: DatabaseConfig::default(),
            telemetry: TelemetryConfig::default(),
            templates: TemplatesConfig::default(),
            email: EmailConfig::default(),
            passwords: PasswordsConfig::default(),
            secrets: SecretsConfig::generate(&mut rng).await?,
            matrix: MatrixConfig::generate(&mut rng),
            policy: PolicyConfig::default(),
            rate_limiting: RateLimitingConfig::default(),
            upstream_oauth2: UpstreamOAuth2Config::default(),
            branding: BrandingConfig::default(),
            captcha: CaptchaConfig::default(),
            account: AccountConfig::default(),
            oauth: OAuthConfig::default(),
            experimental: ExperimentalConfig::default(),
        })
    }

    /// Configuration used in tests
    #[must_use]
    pub fn test() -> Self {
        Self {
            clients: ClientsConfig::default(),
            http: HttpConfig::default(),
            database: DatabaseConfig::default(),
            telemetry: TelemetryConfig::default(),
            templates: TemplatesConfig::default(),
            passwords: PasswordsConfig::default(),
            email: EmailConfig::default(),
            secrets: SecretsConfig::test(),
            matrix: MatrixConfig::test(),
            policy: PolicyConfig::default(),
            rate_limiting: RateLimitingConfig::default(),
            upstream_oauth2: UpstreamOAuth2Config::default(),
            branding: BrandingConfig::default(),
            captcha: CaptchaConfig::default(),
            account: AccountConfig::default(),
            oauth: OAuthConfig::default(),
            experimental: ExperimentalConfig::default(),
        }
    }
}

/// Partial configuration actually used by the server
#[expect(missing_docs)]
#[derive(Debug, Deserialize)]
pub struct AppConfig {
    #[serde(default)]
    pub http: HttpConfig,

    #[serde(default)]
    pub database: DatabaseConfig,

    #[serde(default)]
    pub templates: TemplatesConfig,

    #[serde(default)]
    pub email: EmailConfig,

    pub secrets: SecretsConfig,

    #[serde(default)]
    pub passwords: PasswordsConfig,

    pub matrix: MatrixConfig,

    #[serde(default)]
    pub policy: PolicyConfig,

    #[serde(default)]
    pub rate_limiting: RateLimitingConfig,

    #[serde(default)]
    pub branding: BrandingConfig,

    #[serde(default)]
    pub captcha: CaptchaConfig,

    #[serde(default)]
    pub account: AccountConfig,

    #[serde(default)]
    pub oauth: OAuthConfig,

    #[serde(default)]
    pub experimental: ExperimentalConfig,
}

impl ConfigurationSection for AppConfig {
    fn validate(
        &self,
        figment: &figment::Figment,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
        self.http.validate(figment)?;
        self.database.validate(figment)?;
        self.templates.validate(figment)?;
        self.email.validate(figment)?;
        self.passwords.validate(figment)?;
        self.secrets.validate(figment)?;
        self.matrix.validate(figment)?;
        self.policy.validate(figment)?;
        self.rate_limiting.validate(figment)?;
        self.branding.validate(figment)?;
        self.captcha.validate(figment)?;
        self.account.validate(figment)?;
        self.oauth.validate(figment)?;
        self.experimental.validate(figment)?;

        Ok(())
    }
}

/// Partial config used by the `mas-cli config sync` command
#[expect(missing_docs)]
#[derive(Debug, Deserialize)]
pub struct SyncConfig {
    #[serde(default)]
    pub database: DatabaseConfig,

    pub secrets: SecretsConfig,

    #[serde(default)]
    pub clients: ClientsConfig,

    #[serde(default)]
    pub upstream_oauth2: UpstreamOAuth2Config,
}

impl ConfigurationSection for SyncConfig {
    fn validate(
        &self,
        figment: &figment::Figment,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
        self.database.validate(figment)?;
        self.secrets.validate(figment)?;
        self.clients.validate(figment)?;
        self.upstream_oauth2.validate(figment)?;

        Ok(())
    }
}

/// Client secret config option.
///
/// It either holds the client secret value directly or references a file where
/// the client secret is stored.
#[derive(Clone, Debug)]
pub enum ClientSecret {
    /// Path to the file containing the client secret.
    File(Utf8PathBuf),

    /// Client secret value.
    Value(String),
}

/// Client secret fields as serialized in JSON.
#[derive(JsonSchema, Serialize, Deserialize, Clone, Debug)]
pub struct ClientSecretRaw {
    /// Path to the file containing the client secret. The client secret is used
    /// by the `client_secret_basic`, `client_secret_post` and
    /// `client_secret_jwt` authentication methods.
    #[schemars(with = "Option<String>")]
    #[serde(skip_serializing_if = "Option::is_none")]
    client_secret_file: Option<Utf8PathBuf>,

    /// Alternative to `client_secret_file`: Reads the client secret directly
    /// from the config.
    #[serde(skip_serializing_if = "Option::is_none")]
    client_secret: Option<String>,
}

impl ClientSecret {
    /// Returns the client secret.
    ///
    /// If `client_secret_file` was given, the secret is read from that file.
    ///
    /// # Errors
    ///
    /// Returns an error when the client secret could not be read from file.
    pub async fn value(&self) -> anyhow::Result<String> {
        Ok(match self {
            ClientSecret::File(path) => tokio::fs::read_to_string(path).await?.trim().to_owned(),
            ClientSecret::Value(client_secret) => client_secret.clone(),
        })
    }
}

impl TryFrom<ClientSecretRaw> for Option<ClientSecret> {
    type Error = anyhow::Error;

    fn try_from(value: ClientSecretRaw) -> Result<Self, Self::Error> {
        match (value.client_secret, value.client_secret_file) {
            (None, None) => Ok(None),
            (None, Some(path)) => Ok(Some(ClientSecret::File(path))),
            (Some(client_secret), None) => Ok(Some(ClientSecret::Value(client_secret))),
            (Some(_), Some(_)) => {
                bail!("Cannot specify both `client_secret` and `client_secret_file`")
            }
        }
    }
}

impl From<Option<ClientSecret>> for ClientSecretRaw {
    fn from(value: Option<ClientSecret>) -> Self {
        match value {
            Some(ClientSecret::File(path)) => ClientSecretRaw {
                client_secret_file: Some(path),
                client_secret: None,
            },
            Some(ClientSecret::Value(client_secret)) => ClientSecretRaw {
                client_secret_file: None,
                client_secret: Some(client_secret),
            },
            None => ClientSecretRaw {
                client_secret_file: None,
                client_secret: None,
            },
        }
    }
}
