using System.Net.Http.Headers;
using System.Net.Http.Json;
using CashLineERP.Contracts.Auth;

namespace CashLineERP.Api.Tests;

internal static class HttpClientAuthExtensions
{
    public static Task AuthenticateAsInternalAsync(this HttpClient client)
        => client.AuthenticateAsync("OPS_MKR01", "OpsMkr01!", "INTERNAL");

    public static Task AuthenticateAsFinanceMakerAsync(this HttpClient client)
        => client.AuthenticateAsync("FIN_MKR01", "FinMkr01!", "INTERNAL");

    public static Task AuthenticateAsSupplierAsync(this HttpClient client)
        => client.AuthenticateAsync("SUPPLIER_ADMIN01", "Supplier01!", "EXTERNAL");

    public static Task AuthenticateAsCustomerAsync(this HttpClient client)
        => client.AuthenticateAsync("CUSTOMER_ADMIN01", "Customer01!", "EXTERNAL");

    public static Task AuthenticateAsFinanceCheckerAsync(this HttpClient client)
        => client.AuthenticateAsync("FIN_CHK01", "FinChk01!", "INTERNAL");

    public static Task AuthenticateAsAdministratorAsync(this HttpClient client)
        => client.AuthenticateAsync("administrator@uat.cashline.test", "Admin@12345", "INTERNAL");

    public static async Task AuthenticateAsync(this HttpClient client, string username, string password, string clientType)
    {
        var response = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, password, clientType));
        response.EnsureSuccessStatusCode();

        var payload = await response.Content.ReadFromJsonAsync<LoginResponse>();
        Assert.NotNull(payload);
        Assert.False(string.IsNullOrWhiteSpace(payload!.AccessToken));

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", payload.AccessToken);
    }
}
