use crate::utils::{handle_response, require_token};
use anyhow::Result;
use clap::Subcommand;
use serde_json::json;
use serde_json::Value;
use std::fs;
use std::path::PathBuf;

#[derive(Subcommand)]
pub enum StorageCommands {
    /// List storage backends
    List,
    /// Create a storage backend
    Create {
        name: String,
        /// The type of storage backend (e.g., s3, oci)
        #[arg(long)]
        backend_type: String,
        /// Path to JSON configuration file
        #[arg(long)]
        config: PathBuf,
        #[arg(long)]
        default_sfs: bool,
        #[arg(long)]
        description: Option<String>,
        /// Optional AWS role ARN to assume
        #[arg(long)]
        aws_assume_role_arn: Option<String>,
    },
    /// Get storage backend details
    Get { id: stormchaser_model::BackendId },
    /// Update a storage backend
    Update {
        id: stormchaser_model::BackendId,
        #[arg(long)]
        name: Option<String>,
        /// Path to JSON configuration file
        #[arg(long)]
        config: Option<PathBuf>,
        #[arg(long)]
        default_sfs: Option<bool>,
        #[arg(long)]
        description: Option<String>,
        /// Optional AWS role ARN to assume
        #[arg(long)]
        aws_assume_role_arn: Option<String>,
    },
    /// Delete a storage backend
    Delete { id: stormchaser_model::BackendId },
}

pub async fn handle(
    url: &str,
    token: Option<&str>,
    http_client: &reqwest_middleware::ClientWithMiddleware,
    command: StorageCommands,
) -> Result<()> {
    match command {
        StorageCommands::List => {
            let token = require_token(token)?;
            let res = http_client
                .get(format!("{}/api/v1/storage-backends", url))
                .header("Authorization", format!("Bearer {}", token))
                .send()
                .await?;
            handle_response(res).await?;
        }
        StorageCommands::Create {
            name,
            backend_type,
            config,
            default_sfs,
            description,
            aws_assume_role_arn,
        } => {
            let config_json: Value = serde_json::from_str(&fs::read_to_string(config)?)?;
            let token = require_token(token)?;
            let res = http_client
                .post(format!("{}/api/v1/storage-backends", url))
                .header("Authorization", format!("Bearer {}", token))
                .json(&json!({
                    "name": name,
                    "backend_type": backend_type,
                    "config": config_json,
                    "is_default_sfs": default_sfs,
                    "description": description,
                    "aws_assume_role_arn": aws_assume_role_arn,
                }))
                .send()
                .await?;
            handle_response(res).await?;
        }
        StorageCommands::Get { id } => {
            let token = require_token(token)?;
            let res = http_client
                .get(format!("{}/api/v1/storage-backends/{}", url, id))
                .header("Authorization", format!("Bearer {}", token))
                .send()
                .await?;
            handle_response(res).await?;
        }
        StorageCommands::Update {
            id,
            name,
            config,
            default_sfs,
            description,
            aws_assume_role_arn,
        } => {
            let mut body = json!({});
            if let Some(n) = name {
                body["name"] = json!(n);
            }
            if let Some(c) = config {
                body["config"] = serde_json::from_str(&fs::read_to_string(c)?)?;
            }
            if let Some(d) = default_sfs {
                body["is_default_sfs"] = json!(d);
            }
            if let Some(desc) = description {
                body["description"] = json!(desc);
            }
            if let Some(arn) = aws_assume_role_arn {
                body["aws_assume_role_arn"] = json!(arn);
            }

            let token = require_token(token)?;
            let res = http_client
                .patch(format!("{}/api/v1/storage-backends/{}", url, id))
                .header("Authorization", format!("Bearer {}", token))
                .json(&body)
                .send()
                .await?;
            handle_response(res).await?;
        }
        StorageCommands::Delete { id } => {
            let token = require_token(token)?;
            let res = http_client
                .delete(format!("{}/api/v1/storage-backends/{}", url, id))
                .header("Authorization", format!("Bearer {}", token))
                .send()
                .await?;
            handle_response(res).await?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest_middleware::ClientBuilder;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_storage_list() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/storage-backends"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
            .mount(&server)
            .await;

        let client = ClientBuilder::new(reqwest::Client::new()).build();
        let cmd = StorageCommands::List;

        let result = handle(&server.uri(), Some("test-token"), &client, cmd).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_storage_create() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v1/storage-backends"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "created"})))
            .mount(&server)
            .await;

        use std::io::Write;
        use tempfile::NamedTempFile;
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "{{\"bucket\":\"my-bucket\"}}").unwrap();

        let client = ClientBuilder::new(reqwest::Client::new()).build();
        let cmd = StorageCommands::Create {
            name: "test-storage".to_string(),
            backend_type: "s3".to_string(),
            config: temp_file.path().to_path_buf(),
            default_sfs: true,
            description: None,
            aws_assume_role_arn: None,
        };

        let result = handle(&server.uri(), Some("test-token"), &client, cmd).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_storage_delete() {
        let server = MockServer::start().await;
        let id = stormchaser_model::BackendId::new_v4();
        Mock::given(method("DELETE"))
            .and(path(format!("/api/v1/storage-backends/{}", id)))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "deleted"})))
            .mount(&server)
            .await;

        let client = ClientBuilder::new(reqwest::Client::new()).build();
        let cmd = StorageCommands::Delete { id };

        let result = handle(&server.uri(), Some("test-token"), &client, cmd).await;
        assert!(result.is_ok());
    }
}
