using Baya.Application.Contracts.Identity;
using Baya.Domain.Entities.User;
using Baya.Infrastructure.Identity.Identity.Manager;
using Microsoft.Extensions.DependencyInjection;

namespace Baya.Test.Api;

/// <summary>
/// Logs a user in as an admin: creates the user and grants the seeded <c>admin</c> role <b>before</b>
/// login so the minted access token already carries the admin role claim (role claims are baked at mint
/// time). The dynamic-permission policy grants full access to the admin role.
/// </summary>
internal static class AdminTestClient
{
    public static async Task AuthenticateAsync(BayaApiFactory factory, HttpClient client, string phone)
    {
        using (var scope = factory.Services.CreateScope())
        {
            var userManager = scope.ServiceProvider.GetRequiredService<IAppUserManager>();
            var roleManager = scope.ServiceProvider.GetRequiredService<AppRoleManager>();

            var user = await userManager.GetUserByPhoneNumber(phone);
            if (user is null)
            {
                await userManager.CreateUser(new User { UserName = $"admin_{Guid.NewGuid():N}", PhoneNumber = phone });
                user = await userManager.GetUserByPhoneNumber(phone);
            }

            var adminRole = await roleManager.FindByNameAsync(RoleNames.Admin);
            await userManager.AddUserToRoleAsync(user!, adminRole!);
        }

        var tokens = await AuthTestClient.LoginAsync(factory, client, phone);
        AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
    }
}
