using System.Text.RegularExpressions;

namespace CartWise.Web.Tests;

internal static class WebTestHelpers
{
    public static async Task RegisterAsync(HttpClient client, string email, string displayName, string password = "Sup3rSecret!23")
    {
        var html = await client.GetStringAsync("/Account/Register");
        var token = ExtractAntiForgeryToken(html);

        var form = new Dictionary<string, string>
        {
            ["__RequestVerificationToken"] = token,
            ["DisplayName"] = displayName,
            ["Email"] = email,
            ["Password"] = password,
            ["ConfirmPassword"] = password
        };

        var response = await client.PostAsync("/Account/Register", new FormUrlEncodedContent(form));
        response.EnsureSuccessStatusCode();
    }

    public static async Task CreateHouseholdAsync(HttpClient client, string name)
    {
        var html = await client.GetStringAsync("/household/create");
        var token = ExtractAntiForgeryToken(html);

        var form = new Dictionary<string, string>
        {
            ["__RequestVerificationToken"] = token,
            ["Name"] = name
        };

        var response = await client.PostAsync("/household/create", new FormUrlEncodedContent(form));
        response.EnsureSuccessStatusCode();
    }

    public static string ExtractAntiForgeryToken(string html)
    {
        var match = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"");
        return match.Success ? match.Groups[1].Value : throw new InvalidOperationException("Anti-forgery token not found.");
    }
}
