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;

/// Represents a message queue resource with minimal, portable semantics.
/// Queue integrates with platform-native services (AWS SQS, GCP Pub/Sub, Azure Service Bus).
#[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 Queue {
    /// Identifier for the queue. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
    /// Maximum 64 characters.
    #[builder(start_fn)]
    pub id: String,
}

impl Queue {
    /// The resource type identifier for Queue
    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("queue");

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

/// Outputs generated by a successfully provisioned Queue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct QueueOutputs {
    /// The name of the queue (platform-specific physical name).
    pub queue_name: String,
    /// Platform-specific identifier or URL (e.g., SQS URL, Pub/Sub topic/subscription).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identifier: Option<String>,
}

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

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

// Implementation of ResourceDefinition trait for Queue
impl ResourceDefinition for Queue {
    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 Queue type to use the existing validate_update method
        let new_queue = new_config.as_any().downcast_ref::<Queue>().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_queue.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::<Queue>() == 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_queue_builder() {
        let q = Queue::new("my-queue".to_string()).build();
        assert_eq!(q.id, "my-queue");
    }

    #[test]
    fn test_queue_resource_type() {
        assert_eq!(Queue::RESOURCE_TYPE.as_ref(), "queue");
    }

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

    #[test]
    fn test_queue_validate_update() {
        let original = Queue::new("test-q".to_string()).build();
        let valid_update = Queue::new("test-q".to_string()).build();
        let invalid_update = Queue::new("different-q".to_string()).build();

        assert!(original.validate_update(&valid_update).is_ok());
        assert!(original.validate_update(&invalid_update).is_err());
    }
}
