#![allow(clippy::unwrap_used, clippy::expect_used, clippy::shadow_unrelated, clippy::shadow_reuse)]
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use fxt::auth::token_manager::{FileTokenStorage, TokenStorage};

fn create_test_storage() -> FileTokenStorage {
    // Use default directory - benchmark will measure real-world performance
    FileTokenStorage::new().unwrap()
}

fn bench_store_token_encrypted(c: &mut Criterion) {
    c.bench_function("store_token_encrypted", |b| {
        let storage = create_test_storage();
        let token = "test_token_12345678901234567890123456789012345678901234567890";

        b.iter(|| {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                storage.store_access_token(black_box(token)).await.unwrap();
            });
        });
    });
}

fn bench_retrieve_token_encrypted(c: &mut Criterion) {
    c.bench_function("retrieve_token_encrypted", |b| {
        let storage = create_test_storage();
        let token = "test_token_12345678901234567890123456789012345678901234567890";

        // Store token first
        let setup_rt = tokio::runtime::Runtime::new().unwrap();
        setup_rt.block_on(async {
            storage.store_access_token(token).await.unwrap();
        });

        b.iter(|| {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                black_box(storage.get_access_token().await.unwrap());
            });
        });
    });
}

fn bench_roundtrip_encrypted(c: &mut Criterion) {
    c.bench_function("roundtrip_encrypted", |b| {
        let token = "test_token_12345678901234567890123456789012345678901234567890";

        b.iter(|| {
            let storage = create_test_storage();
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                storage.store_access_token(black_box(token)).await.unwrap();
                black_box(storage.get_access_token().await.unwrap());
            });
        });
    });
}

fn bench_key_derivation(c: &mut Criterion) {
    use fxt::auth::KeyManager;

    c.bench_function("key_derivation_first_call", |b| {
        b.iter(|| {
            let mut manager = KeyManager::new();
            black_box(manager.derive_key().unwrap());
        });
    });

    // Benchmark cached key derivation
    c.bench_function("key_derivation_cached", |b| {
        let mut manager = KeyManager::new();
        // Prime the cache
        manager.derive_key().unwrap();

        b.iter(|| {
            black_box(manager.derive_key().unwrap());
        });
    });
}

criterion_group!(
    benches,
    bench_store_token_encrypted,
    bench_retrieve_token_encrypted,
    bench_roundtrip_encrypted,
    bench_key_derivation
);
criterion_main!(benches);
