namespace Books.E2E.Tests.Infrastructure;

/// <summary>
/// Main fixture for E2E tests.
/// Provides configuration and shared resources.
/// Does NOT start any servers - tests run against pre-existing URLs.
/// </summary>
public class E2ETestFixture : IAsyncLifetime
{
    public E2EConfiguration Configuration { get; } = new();
    public HttpClient ApiClient { get; private set; } = null!;

    public async Task InitializeAsync()
    {
        // Create HTTP client for API calls
        var handler = new HttpClientHandler
        {
            // Accept self-signed certs for localhost
            ServerCertificateCustomValidationCallback = (_, _, _, _) => true
        };

        ApiClient = new HttpClient(handler)
        {
            BaseAddress = new Uri(Configuration.BackendUrl)
        };

        // Verify backend is reachable
        try
        {
            var response = await ApiClient.GetAsync("/graphql?query={__typename}");
            Console.WriteLine($"[E2ETestFixture] Backend health check: {response.StatusCode}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[E2ETestFixture] WARNING: Backend not reachable at {Configuration.BackendUrl}: {ex.Message}");
            Console.WriteLine("[E2ETestFixture] Make sure the backend is running before executing E2E tests.");
        }

        // Verify frontend is reachable
        try
        {
            using var frontendClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
            var response = await frontendClient.GetAsync(Configuration.FrontendUrl);
            Console.WriteLine($"[E2ETestFixture] Frontend health check: {response.StatusCode}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[E2ETestFixture] WARNING: Frontend not reachable at {Configuration.FrontendUrl}: {ex.Message}");
            Console.WriteLine("[E2ETestFixture] Make sure the frontend is running before executing E2E tests.");
        }

        await Task.CompletedTask;
    }

    public Task DisposeAsync()
    {
        ApiClient?.Dispose();
        return Task.CompletedTask;
    }
}
