//! Debug test for FileTokenStorage

// Suppress false-positive unused_crate_dependencies warnings
// dev-dependencies are shared across ALL test targets in the crate
// This test may not use all deps, but they are required by other integration tests
#![allow(unused_crate_dependencies)]
#![allow(clippy::tests_outside_test_module, clippy::str_to_string, clippy::non_ascii_literal, clippy::shadow_unrelated, clippy::shadow_reuse, clippy::unwrap_used, clippy::expect_used, clippy::assertions_on_result_states, clippy::use_debug, clippy::let_underscore_must_use, clippy::string_add, clippy::string_add_assign, clippy::wildcard_enum_match_arm, clippy::unseparated_literal_suffix, clippy::indexing_slicing, clippy::doc_markdown, clippy::similar_names, clippy::impl_trait_in_params, unused_imports, dead_code, clippy::panic, clippy::let_underscore_future, clippy::manual_flatten)]

use anyhow::Result;
use fxt::auth::token_manager::{FileTokenStorage, TokenStorage};

#[tokio::test]
async fn debug_file_storage() -> Result<()> {
    let storage = FileTokenStorage::new()?;

    println!("\n=== FileTokenStorage Debug Test ===");

    // Store token
    let test_token = "debug_test_token_12345";
    println!("1. Storing token: {}", test_token);

    match storage.store_access_token(test_token).await {
        Ok(()) => println!("   ✓ Store succeeded"),
        Err(e) => {
            println!("   ✗ Store failed: {}", e);
            return Err(e);
        },
    }

    // Immediately retrieve
    println!("2. Retrieving token immediately...");
    match storage.get_access_token().await {
        Ok(Some(token)) => {
            println!("   ✓ Retrieved: {}", token);
            assert_eq!(token, test_token, "Tokens don't match!");
        },
        Ok(None) => {
            println!("   ✗ Retrieved None (token not found)");

            // Debug: Check file paths
            let token_dir = std::env::var("HOME")
                .or_else(|_| std::env::var("USERPROFILE"))
                .expect("Cannot find home directory")
                + "/.config/foxhunt-fxt/tokens";

            println!("\n3. Debug file system:");
            println!("   Token dir: {}", token_dir);

            // Check if directory exists
            if std::path::Path::new(&token_dir).exists() {
                println!("   ✓ Directory exists");

                // List files
                if let Ok(entries) = std::fs::read_dir(&token_dir) {
                    println!("   Files in directory:");
                    for entry in entries {
                        if let Ok(entry) = entry {
                            println!("     - {}", entry.path().display());

                            // Try to read the file
                            if let Ok(contents) = std::fs::read_to_string(entry.path()) {
                                println!(
                                    "       Contents (first 50 chars): {}",
                                    &contents.chars().take(50).collect::<String>()
                                );
                            }
                        }
                    }
                } else {
                    println!("   ✗ Cannot list directory");
                }
            } else {
                println!("   ✗ Directory does not exist");
            }

            panic!("Token retrieval returned None");
        },
        Err(e) => {
            println!("   ✗ Retrieval failed: {}", e);
            return Err(e);
        },
    }

    // Clean up
    storage.clear_access_token().await?;
    println!("4. Cleanup complete");

    Ok(())
}
