//! REST API Test
//!
//! Run with: cargo test --test api_test -- --nocapture --ignored
//! Set CHAINSTREAM_ACCESS_TOKEN environment variable for testing

use chainstream_sdk::{openapi, CHAINSTREAM_BASE_URL};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use std::env;

const TEST_ACCESS_TOKEN: &str = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtleXN0b3JlLUNIQU5HRS1NRSJ9.eyJqdGkiOiJJQWxZMGdNRGJ0ZW5jNnNhT1dheDEiLCJzdWIiOiJIR2hWbmpiSWlheDFIcDNUakdUd083WU9FUkJURXRwaSIsImlhdCI6MTc3MDAxMzc0MywiZXhwIjoxNzcwMTAwMTQzLCJjbGllbnRfaWQiOiJIR2hWbmpiSWlheDFIcDNUakdUd083WU9FUkJURXRwaSIsImlzcyI6Imh0dHBzOi8vZGV4LmFzaWEuYXV0aC5jaGFpbnN0cmVhbS5pby8iLCJhdWQiOiJodHRwczovL2FwaS5kZXguY2hhaW5zdHJlYW0uaW8ifQ.TVY_FN1MdMogamLvXnYlVoLSXTZpX1b1c3xtUJNB5peUrZCTY_nLB8oOJ-ysBz3qsZhnUpUnX4LKSfuyGXDlfyasJG5c7yrj5zEYUZfkFKxG7PTtNLzXTF-4z0J7VnkbA-VUz1c1z3gaGDf3TFpo_Mfl6Zqf0v_CgDugciJ0ZbJS68gy_EaMXSBHwU7mm_vC2FUFkUfa8qwL3xvEEbOYxIQXJyHmqddnJew6nSyifHEqC_tSYj-o8GDP6PTbfOwqiyB_-T8valMwygFXYMgGstOUnITgNvJE4ciya3yalLuWONoA3LtoDzAq3wABr-0cyIbHVvQJkDT0VjqvJOv89Q";

fn get_access_token() -> String {
    env::var("CHAINSTREAM_ACCESS_TOKEN").unwrap_or_else(|_| TEST_ACCESS_TOKEN.to_string())
}

/// Middleware to add Bearer token to requests
struct BearerAuthMiddleware {
    token: String,
}

#[async_trait::async_trait]
impl reqwest_middleware::Middleware for BearerAuthMiddleware {
    async fn handle(
        &self,
        mut req: reqwest::Request,
        extensions: &mut http::Extensions,
        next: reqwest_middleware::Next<'_>,
    ) -> reqwest_middleware::Result<reqwest::Response> {
        req.headers_mut().insert(
            reqwest::header::AUTHORIZATION,
            format!("Bearer {}", self.token).parse().unwrap(),
        );
        next.run(req, extensions).await
    }
}

#[tokio::test]
#[ignore] // Run with: cargo test --test api_test -- --nocapture --ignored
async fn test_get_supported_blockchains() {
    let access_token = get_access_token();

    println!("===========================================");
    println!("Testing GET /v1/blockchain");
    println!("Base URL: {}", CHAINSTREAM_BASE_URL);
    println!("===========================================\n");

    // Create HTTP client with Bearer token middleware
    let http_client: ClientWithMiddleware = ClientBuilder::new(reqwest::Client::new())
        .with(BearerAuthMiddleware {
            token: access_token,
        })
        .build();

    // Create OpenAPI client
    let client = openapi::Client::new_with_client(CHAINSTREAM_BASE_URL, http_client);

    // Call API
    let result = client.get_supported_blockchains().send().await;

    match result {
        Ok(response) => {
            println!("Response status: {}", response.status());
            let blockchains = response.into_inner();
            println!("\nSupported blockchains:");
            println!("{:#?}", blockchains);
        }
        Err(e) => {
            eprintln!("API call failed: {:?}", e);
        }
    }

    println!("\n===========================================");
    println!("Test completed");
    println!("===========================================");
}
