using System.Diagnostics;
using Microsoft.Playwright;

namespace Books.E2E.Tests.Infrastructure;

/// <summary>
/// Shared Playwright browser instance for E2E tests.
/// Implements IAsyncLifetime for xUnit async fixture pattern.
/// </summary>
public class PlaywrightFixture : IAsyncLifetime
{
    private IPlaywright? _playwright;
    private IBrowser? _browser;

    public IBrowser Browser => _browser ?? throw new InvalidOperationException("Browser not initialized. Did you forget to call InitializeAsync?");

    public async Task InitializeAsync()
    {
        Console.WriteLine("[PlaywrightFixture] Initializing Playwright...");

        _playwright = await Playwright.CreateAsync();

        var launchOptions = new BrowserTypeLaunchOptions
        {
            Headless = !Debugger.IsAttached,
            SlowMo = Debugger.IsAttached ? 100 : 0
        };

        _browser = await _playwright.Chromium.LaunchAsync(launchOptions);

        Console.WriteLine($"[PlaywrightFixture] Browser launched (headless: {launchOptions.Headless})");
    }

    public async Task DisposeAsync()
    {
        if (_browser != null)
        {
            await _browser.CloseAsync();
            Console.WriteLine("[PlaywrightFixture] Browser closed");
        }

        _playwright?.Dispose();
    }

    /// <summary>
    /// Creates a new browser context with E2E test settings.
    /// Each test should get its own context for isolation.
    /// </summary>
    public async Task<IBrowserContext> CreateContextAsync()
    {
        return await Browser.NewContextAsync(new BrowserNewContextOptions
        {
            IgnoreHTTPSErrors = true,
            ViewportSize = new ViewportSize { Width = 1920, Height = 1080 },
            Locale = "da-DK",
            TimezoneId = "Europe/Copenhagen"
        });
    }
}
