using System.Net;
using System.Net.Http.Json;

namespace JSMR.UI.Blazor.Services;

public class AuthenticationClient(HttpClient http)
{
    public async Task<bool> LoginAsync(string username, string password, CancellationToken ct = default)
    {
        var resp = await http.PostAsJsonAsync("/auth/login", new { username, password }, ct);
        return resp.IsSuccessStatusCode;
    }

    public async Task LogoutAsync(CancellationToken ct = default)
        => await http.PostAsync("/auth/logout", content: null, ct);

    public async Task<MeResponse?> GetMeAsync(CancellationToken ct = default)
    {
        var resp = await http.GetAsync("/api/me", ct);

        if (resp.StatusCode == HttpStatusCode.Unauthorized)
            return null;

        resp.EnsureSuccessStatusCode();
        return await resp.Content.ReadFromJsonAsync<MeResponse>(cancellationToken: ct);
    }

    public sealed record MeResponse(string? Name, string? Id, string? Role);
}