//!
//! Defines stack-level settings and management configurations for different cloud platforms.
//! These settings customize deployment behavior and cross-account/cross-tenant access patterns.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// AWS management configuration extracted from stack settings
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AwsManagementConfig {
    /// The managing AWS IAM role ARN that can assume cross-account roles
    pub managing_role_arn: String,
}

/// GCP management configuration extracted from stack settings
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct GcpManagementConfig {
    /// Service account email for management roles
    pub service_account_email: String,
}

/// Azure management configuration extracted from stack settings
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AzureManagementConfig {
    /// The managing Azure Tenant ID for cross-tenant access
    pub managing_tenant_id: String,
    /// OIDC issuer URL for federated identity credential creation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oidc_issuer: Option<String>,
    /// OIDC subject claim for federated identity credential creation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oidc_subject: Option<String>,
    /// Management service principal object ID for local development fallback
    #[serde(skip_serializing_if = "Option::is_none")]
    pub management_principal_id: Option<String>,
}

/// Management configuration for different cloud platforms.
///
/// Platform-derived configuration for cross-account/cross-tenant access.
/// This is NOT user-specified - it's derived from the Manager's ServiceAccount.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "platform")]
pub enum ManagementConfig {
    /// AWS management configuration
    Aws(AwsManagementConfig),
    /// GCP management configuration  
    Gcp(GcpManagementConfig),
    /// Azure management configuration
    Azure(AzureManagementConfig),
    /// Kubernetes management configuration (minimal for now)
    Kubernetes,
}

/// Network configuration for the stack.
///
/// Controls how VPC/VNet networking is provisioned. Users configure this in
/// `StackSettings`; the Network resource itself is auto-generated by preflights.
///
/// ## Egress policy
///
/// Container cluster VMs are configured for egress based on the mode:
///
/// - `UseDefault` → VMs get ephemeral public IPs (no NAT is provisioned)
/// - `Create` → VMs use private IPs; Alien provisions a NAT gateway for outbound access
/// - `ByoVpc*` / `ByoVnet*` → no public IPs assigned; customer manages egress
///
/// For production workloads, use `Create`. For fast dev/test iteration, `UseDefault` is
/// sufficient. For environments with existing VPCs, use the appropriate `ByoVpc*` variant.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum NetworkSettings {
    /// Use the cloud provider's default VPC/network.
    ///
    /// Designed for fast dev/test provisioning. No isolated VPC is created, so there
    /// is nothing to wait for or clean up. VMs receive ephemeral public IPs for internet
    /// access — no NAT gateway is provisioned.
    ///
    /// - **AWS**: Discovers the account's default VPC. Subnets are public with auto-assigned IPs.
    /// - **GCP**: Discovers the project's `default` network and regional subnet. Instance
    ///   templates include an `AccessConfig` to assign an ephemeral external IP.
    /// - **Azure**: Azure has no default VNet, so one is created along with a NAT Gateway.
    ///   VMs stay private and use NAT for egress.
    ///
    /// Not recommended for production. Use `Create` instead.
    #[serde(rename = "use-default")]
    UseDefault,

    /// Create a new isolated VPC/VNet with a managed NAT gateway.
    ///
    /// All networking infrastructure is provisioned by Alien and cleaned up on delete.
    /// VMs use private IPs only; all outbound traffic routes through the NAT gateway.
    ///
    /// Recommended for production deployments.
    #[serde(rename = "create")]
    Create {
        /// VPC/VNet CIDR block. If not specified, auto-generated from stack ID
        /// to reduce conflicts (e.g., "10.{hash}.0.0/16").
        #[serde(skip_serializing_if = "Option::is_none")]
        cidr: Option<String>,

        /// Number of availability zones (default: 2).
        #[serde(default = "default_availability_zones")]
        availability_zones: u8,
    },

    /// Use an existing VPC (AWS).
    ///
    /// Alien validates the references but creates no networking infrastructure.
    /// The customer is responsible for routing and egress (NAT, proxy, VPN, etc.).
    #[serde(rename = "byo-vpc-aws")]
    ByoVpcAws {
        /// The ID of the existing VPC
        vpc_id: String,
        /// IDs of public subnets (required for public ingress)
        public_subnet_ids: Vec<String>,
        /// IDs of private subnets
        private_subnet_ids: Vec<String>,
        /// Optional security group IDs to use
        #[serde(default)]
        security_group_ids: Vec<String>,
    },

    /// Use an existing VPC (GCP).
    ///
    /// Alien validates the references but creates no networking infrastructure.
    /// The customer is responsible for routing and egress (Cloud NAT, proxy, VPN, etc.).
    #[serde(rename = "byo-vpc-gcp")]
    ByoVpcGcp {
        /// The name of the existing VPC network
        network_name: String,
        /// The name of the subnet to use
        subnet_name: String,
        /// The region of the subnet
        region: String,
    },

    /// Use an existing VNet (Azure).
    ///
    /// Alien validates the references but creates no networking infrastructure.
    /// The customer is responsible for routing and egress (NAT Gateway, proxy, VPN, etc.).
    #[serde(rename = "byo-vnet-azure")]
    ByoVnetAzure {
        /// The full resource ID of the existing VNet
        vnet_resource_id: String,
        /// Name of the public subnet within the VNet
        public_subnet_name: String,
        /// Name of the private subnet within the VNet
        private_subnet_name: String,
    },
}

fn default_availability_zones() -> u8 {
    2
}

/// Deployment model: how updates are delivered to the remote environment.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum DeploymentModel {
    /// Manager pushes updates via cross-account access.
    /// Available for AWS, GCP, Azure only.
    #[default]
    Push,
    /// Agent in remote environment pulls updates.
    /// Available for all platforms (AWS, GCP, Azure, Kubernetes, Local).
    Pull,
}

/// How updates are delivered to the deployment.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "kebab-case")]
pub enum UpdatesMode {
    /// Updates deploy automatically (default).
    #[default]
    Auto,
    /// Updates require explicit approval before deployment.
    ApprovalRequired,
}

/// How telemetry (logs, metrics, traces) is handled.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "kebab-case")]
pub enum TelemetryMode {
    /// No telemetry permissions. Data will not be collected.
    Off,
    /// Telemetry flows automatically (default).
    #[default]
    Auto,
    /// Telemetry requires explicit approval before collection begins.
    ApprovalRequired,
}

impl TelemetryMode {
    /// Returns true if telemetry is enabled (Auto or ApprovalRequired).
    pub fn is_enabled(&self) -> bool {
        !matches!(self, TelemetryMode::Off)
    }
}

/// How heartbeat health checks are handled.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "kebab-case")]
pub enum HeartbeatsMode {
    /// No heartbeat permissions. Health checks disabled.
    Off,
    /// Heartbeat enabled (default).
    #[default]
    On,
}

impl HeartbeatsMode {
    /// Returns true if heartbeat is enabled.
    pub fn is_enabled(&self) -> bool {
        matches!(self, HeartbeatsMode::On)
    }
}

/// Domain configuration for the stack.
///
/// When `custom_domains` is set, the specified resources use customer-provided
/// domains and certificates. Otherwise, Alien auto-generates domains.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct DomainSettings {
    /// Custom domain configuration per resource ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_domains: Option<HashMap<String, CustomDomainConfig>>,
}

/// Custom domain configuration for a single resource.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CustomDomainConfig {
    /// Fully qualified domain name to use.
    pub domain: String,
    /// Customer-provided certificate reference.
    pub certificate: CustomCertificateConfig,
}

/// Platform-specific certificate references for custom domains.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CustomCertificateConfig {
    /// AWS ACM certificate ARN
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aws: Option<AwsCustomCertificateConfig>,
    /// GCP Certificate Manager certificate name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gcp: Option<GcpCustomCertificateConfig>,
    /// Azure Key Vault certificate ID
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub azure: Option<AzureCustomCertificateConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AwsCustomCertificateConfig {
    pub certificate_arn: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct GcpCustomCertificateConfig {
    pub certificate_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct AzureCustomCertificateConfig {
    pub key_vault_certificate_id: String,
}

/// User-customizable deployment settings specified at deploy time.
///
/// These settings are provided by the customer via CloudFormation parameters,
/// Terraform attributes, CLI flags, or Helm values. They customize how the
/// deployment runs and what capabilities are enabled.
///
/// **Key distinction**: StackSettings is user-customizable, while ManagementConfig
/// is platform-derived (from the Manager's ServiceAccount).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct StackSettings {
    /// Network configuration for the stack (VPC/VNet settings).
    /// If `None`, an isolated VPC with NAT is auto-created when the stack has resources
    /// that require networking (e.g., containers). Set explicitly to customize:
    /// `UseDefault` for the provider's default network (fast, dev/test only),
    /// `Create` for an isolated VPC with managed NAT (production), or `ByoVpc*`
    /// to reference an existing customer-managed VPC.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkSettings>,

    /// Domain configuration (future).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domains: Option<DomainSettings>,

    /// Deployment model: push (Manager) or pull (Agent).
    /// Default: Push.
    /// - Push: Manager drives updates. For cloud platforms, requires cross-account
    ///   credentials established during initial setup. For push-mode local
    ///   deployments (currently `alien dev`), the manager has direct access —
    ///   no bootstrap needed.
    /// - Pull: Agent in the target environment drives updates via polling.
    ///   Required for Kubernetes and remote local deployments.
    #[serde(default, skip_serializing_if = "is_default_deployment_model")]
    pub deployment_model: DeploymentModel,

    /// How updates are delivered.
    /// - auto: Updates deploy automatically (default)
    /// - approval-required: Updates wait for explicit approval
    #[serde(default, skip_serializing_if = "is_default_updates_mode")]
    pub updates: UpdatesMode,

    /// How telemetry (logs, metrics, traces) is handled.
    /// - off: No telemetry permissions
    /// - auto: Telemetry flows automatically (default)
    /// - approval-required: Telemetry waits for explicit approval
    #[serde(default, skip_serializing_if = "is_default_telemetry_mode")]
    pub telemetry: TelemetryMode,

    /// How heartbeat health checks are handled.
    /// - off: No heartbeat permissions
    /// - on: Heartbeat enabled (default)
    #[serde(default, skip_serializing_if = "is_default_heartbeats_mode")]
    pub heartbeats: HeartbeatsMode,

    /// External bindings for pre-existing infrastructure.
    /// Allows using existing resources (MinIO, Redis, shared Container Apps
    /// Environment, etc.) instead of having Alien provision them.
    /// Required for Kubernetes platform, optional for cloud platforms.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<Object>))]
    pub external_bindings: Option<crate::ExternalBindings>,
}

fn is_default_deployment_model(model: &DeploymentModel) -> bool {
    *model == DeploymentModel::default()
}

fn is_default_updates_mode(mode: &UpdatesMode) -> bool {
    *mode == UpdatesMode::default()
}

fn is_default_telemetry_mode(mode: &TelemetryMode) -> bool {
    *mode == TelemetryMode::default()
}

fn is_default_heartbeats_mode(mode: &HeartbeatsMode) -> bool {
    *mode == HeartbeatsMode::default()
}
