using Microsoft.Playwright;

namespace IWS5.Autotest.IWS5.UiTests.Base
{
    public static class BrowserManager
    {
        private static IPlaywright _playwright;
        private static IBrowser _browser;
        private static IPage _page;

        public static async Task<IPage> LaunchBrowserAsync(string url)
        {
            var config = await ConfigLoader.LoadConfigurationsAsync();

            _playwright = await Playwright.CreateAsync();
            _browser = await _playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = config.IsHeadless
            });

            var context = await _browser.NewContextAsync();
            _page = await context.NewPageAsync();

            Console.WriteLine($"Browser opened and navigating to: {url}");
            await _page.GotoAsync(url);

            return _page;
        }

        public static async Task<IPage> GetPageAsync()
        {
            if (_page == null)
                throw new Exception("Browser is not launched. Call LaunchBrowserAsync() first.");

            return _page;
        }

        public static async Task CloseBrowserAsync()
        {
            if (_browser != null)
            {
                await _browser.CloseAsync();
                _playwright.Dispose();
                Console.WriteLine("Browser is closed");
            }
        }
    }
}
