use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::Debug;

/// Represents a service activation that can be enabled on cloud platforms.
/// For GCP: enables project services (e.g., iam.googleapis.com, compute.googleapis.com).
/// For Azure: registers resource providers (e.g., Microsoft.DocumentDB, Microsoft.Storage).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct ServiceActivation {
    /// Identifier for the service activation. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,

    /// The service identifier to activate.
    /// - For GCP: service name (e.g., "iam.googleapis.com", "compute.googleapis.com")
    /// - For Azure: resource provider namespace (e.g., "Microsoft.DocumentDB", "Microsoft.Storage")
    pub service_name: String,
}

impl ServiceActivation {
    /// The resource type identifier for Service Activations
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("service_activation");

    /// Returns the service's unique identifier.
    pub fn id(&self) -> &str {
        &self.id
    }
}

/// Outputs generated by a successfully activated service.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ServiceActivationOutputs {
    /// The name of the service.
    pub service_name: String,
    /// Whether the service is currently activated/enabled.
    pub activated: bool,
}

impl ResourceOutputsDefinition for ServiceActivationOutputs {
    fn get_resource_type(&self) -> ResourceType {
        ServiceActivation::RESOURCE_TYPE.clone()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
        Box::new(self.clone())
    }

    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
        other.as_any().downcast_ref::<ServiceActivationOutputs>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

// Implementation of ResourceDefinition trait for ServiceActivation
impl ResourceDefinition for ServiceActivation {
    fn get_resource_type(&self) -> ResourceType {
        Self::RESOURCE_TYPE
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn get_dependencies(&self) -> Vec<ResourceRef> {
        Vec::new()
    }

    fn validate_update(&self, _new_config: &dyn ResourceDefinition) -> Result<()> {
        Err(AlienError::new(ErrorData::InvalidResourceUpdate {
            resource_id: self.id.clone(),
            reason: "Service activations cannot be updated once created".to_string(),
        }))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
        Box::new(self.clone())
    }

    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
        other.as_any().downcast_ref::<ServiceActivation>() == Some(self)
    }

    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
        serde_json::to_value(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_activation_creation() {
        let service = ServiceActivation::new("enable-iam".to_string())
            .service_name("iam.googleapis.com".to_string())
            .build();

        assert_eq!(service.id, "enable-iam");
        assert_eq!(service.service_name, "iam.googleapis.com");
    }
}
