using System.Net.Http.Json;

namespace Baya.Test.Api;

/// <summary>
/// Logs a user in, grants a public role, then refreshes so the bearer token carries the new role claim
/// (role claims are baked into the access token at mint time — see backend-phase-2). Uses one OTP verify
/// plus one refresh per call to stay inside the OTP endpoint's per-IP rate-limit budget.
/// </summary>
internal static class ProfileTestClient
{
    public static async Task AuthenticateAsync(BayaApiFactory factory, HttpClient client, string phone, string role)
    {
        var tokens = await AuthTestClient.LoginAsync(factory, client, phone);

        AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
        var select = await client.PostAsJsonAsync("/api/v1/me/select_role", new { role });
        select.EnsureSuccessStatusCode();

        var refreshToken = tokens.GetProperty("refreshToken").GetString()!;
        var refreshed = await client.PostAsJsonAsync("/api/v1/auth/refresh", new { refreshToken });
        refreshed.EnsureSuccessStatusCode();

        var data = await AuthTestClient.ReadDataAsync(refreshed);
        AuthTestClient.UseBearer(client, data.GetProperty("accessToken").GetString()!);
    }
}
