//! Integration test: GCS backend honours a configured `endpoint`.
//!
//! Points a `GcsBackend` at a harness-provided fake-gcs-server emulator (a Dagger-bound
//! service in CI via `GCS_ENDPOINT`; a local spawn with the `local-testcontainers`
//! feature) through `new_with_endpoint`, and round-trips an upload/download. Before the
//! #326 fix the backend hardcoded `storage.googleapis.com` and ignored the endpoint, so
//! this could not reach the emulator.
//!
//! Skips cleanly when no GCS endpoint is available.
#![cfg(feature = "gcs")]
#![allow(clippy::print_stdout, clippy::print_stderr)] // Reason: test diagnostics

use fraiseql_storage::GcsBackend;

#[tokio::test]
async fn gcs_endpoint_override_round_trip() {
    let Some(svc) = fraiseql_test_support::gcs().await else {
        eprintln!("SKIP gcs_endpoint_override_round_trip: no GCS_ENDPOINT");
        return;
    };
    // SAFETY: edition 2021 set_var; nextest runs each test in its own process.
    // fake-gcs-server ignores the token value but the backend requires one.
    std::env::set_var("GOOGLE_CLOUD_TOKEN", "fake-gcs-token");

    let endpoint = svc.url().to_string();

    // fake-gcs-server starts with no buckets; create the target bucket through
    // its standard JSON API (no auth required on the emulator).
    let http = reqwest::Client::new();
    let resp = http
        .post(format!("{endpoint}/storage/v1/b?project=test-project"))
        .json(&serde_json::json!({ "name": "test-bucket" }))
        .send()
        .await
        .expect("create bucket request");
    assert!(resp.status().is_success(), "bucket creation failed: {}", resp.status());

    let backend = GcsBackend::new_with_endpoint("test-bucket", Some(&endpoint))
        .expect("GcsBackend::new_with_endpoint should accept the emulator URL");

    let key = "hello.txt";
    let body = b"hello gcs".to_vec();
    backend.upload(key, &body, "text/plain").await.expect("upload");

    let fetched = backend.download(key).await.expect("download");
    assert_eq!(fetched, body);
}
