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

/// Represents a key-value storage resource that provides a minimal, platform-agnostic API
/// compatible across DynamoDB, Firestore, Redis, and Azure Table 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 Kv {
    /// Identifier for the KV store. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,
}

impl Kv {
    /// The resource type identifier for KV
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("kv");

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

/// Outputs generated by a successfully provisioned KV store.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct KvOutputs {
    /// The name of the KV store (may be platform-specific).
    pub store_name: String,
    /// Platform-specific identifier (e.g., DynamoDB table ARN, Redis endpoint).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identifier: Option<String>,
    /// Platform-specific endpoint URL for direct access (if applicable).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
}

impl ResourceOutputsDefinition for KvOutputs {
    fn get_resource_type(&self) -> ResourceType {
        Kv::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::<KvOutputs>() == Some(self)
    }

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

// Implementation of ResourceDefinition trait for Kv
impl ResourceDefinition for Kv {
    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<()> {
        // Downcast to Kv type to use the existing validate_update method
        let new_kv = new_config.as_any().downcast_ref::<Kv>().ok_or_else(|| {
            AlienError::new(ErrorData::UnexpectedResourceType {
                resource_id: self.id.clone(),
                expected: Self::RESOURCE_TYPE,
                actual: new_config.get_resource_type(),
            })
        })?;

        if self.id != new_kv.id {
            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
                resource_id: self.id.clone(),
                reason: "the 'id' field is immutable".to_string(),
            }));
        }
        Ok(())
    }

    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::<Kv>() == 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_kv_builder() {
        let kv = Kv::new("my-kv".to_string()).build();
        assert_eq!(kv.id, "my-kv");
    }

    #[test]
    fn test_kv_resource_type() {
        assert_eq!(Kv::RESOURCE_TYPE.as_ref(), "kv");
    }

    #[test]
    fn test_kv_resource_definition() {
        let kv = Kv::new("test-kv".to_string()).build();
        assert_eq!(kv.get_resource_type(), Kv::RESOURCE_TYPE);
        assert_eq!(kv.id(), "test-kv");
        assert!(kv.get_dependencies().is_empty());
    }

    #[test]
    fn test_kv_validate_update() {
        let original = Kv::new("test-kv".to_string()).build();
        let valid_update = Kv::new("test-kv".to_string()).build();
        let invalid_update = Kv::new("different-kv".to_string()).build();

        // Same ID should be valid
        assert!(original.validate_update(&valid_update).is_ok());

        // Different ID should be invalid
        assert!(original.validate_update(&invalid_update).is_err());
    }

    #[test]
    fn test_kv_outputs_serialization() {
        let outputs = KvOutputs {
            store_name: "my-kv-store".to_string(),
            identifier: Some(
                "arn:aws:dynamodb:us-east-1:123456789012:table/my-kv-store".to_string(),
            ),
            endpoint: Some("https://my-kv-store.table.core.windows.net".to_string()),
        };

        let json = serde_json::to_string(&outputs).unwrap();
        let deserialized: KvOutputs = serde_json::from_str(&json).unwrap();
        assert_eq!(outputs, deserialized);
    }
}
