using Microsoft.Playwright;
using Xunit;

namespace ZB.MOM.WW.OtOpcUa.Admin.E2ETests;

/// <summary>
///     One Playwright runtime + Chromium browser for the whole E2E suite. Tests
///     open a fresh <see cref="IBrowserContext"/> per fixture so cookies + localStorage
///     stay isolated. Browser install is a one-time step:
///     <c>pwsh tests/ZB.MOM.WW.OtOpcUa.Admin.E2ETests/bin/Debug/net10.0/playwright.ps1 install chromium</c>.
///     When the browser binary isn't present the suite reports a <see cref="PlaywrightBrowserMissingException"/>
///     so CI can distinguish missing-browser from real test failure.
/// </summary>
public sealed class PlaywrightFixture : IAsyncLifetime
{
    public IPlaywright Playwright { get; private set; } = null!;
    public IBrowser Browser { get; private set; } = null!;

    public async ValueTask InitializeAsync()
    {
        Playwright = await Microsoft.Playwright.Playwright.CreateAsync();
        try
        {
            Browser = await Playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true });
        }
        catch (PlaywrightException ex) when (ex.Message.Contains("Executable doesn't exist"))
        {
            throw new PlaywrightBrowserMissingException(ex.Message);
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (Browser is not null) await Browser.CloseAsync();
        Playwright?.Dispose();
    }
}

/// <summary>
///     Thrown by <see cref="PlaywrightFixture"/> when Chromium isn't installed. Tests
///     catching this mark themselves as "skipped" rather than "failed", so CI without
///     the install step stays green.
/// </summary>
public sealed class PlaywrightBrowserMissingException(string message) : Exception(message);
