using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using BlazorPolicyAuth.Models.ViewModels;
using Microsoft.AspNetCore.Components.Authorization;

namespace BlazorPolicyAuth.App.Services.AuthService;

public class AuthService(HttpClient httpClient, AuthenticationStateProvider authenticationStateProvider)
    : IAuthService
{
    public async Task<ServiceResponse<int>> Register(UserRegister request)
    {
        var result = await httpClient.PostAsJsonAsync("api/auth/register", request);
        return await ReadResponse<int>(result);
    }

    public async Task<ServiceResponse<string>> Login(UserLogin request)
    {
        var result = await httpClient.PostAsJsonAsync("api/auth/login", request);
        return await ReadResponse<string>(result);
    }

    public async Task<ServiceResponse<bool>> ChangePassword(UserChangePassword request)
    {
        var result = await httpClient.PostAsJsonAsync("api/auth/change-password", request.Password);
        return await ReadResponse<bool>(result);
    }

    public async Task<bool> IsUserAuthenticated()
    {
        return (await authenticationStateProvider.GetAuthenticationStateAsync()).User.Identity.IsAuthenticated;
    }

    private async Task<ServiceResponse<T>> ReadResponse<T>(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
            return await response.Content.ReadFromJsonAsync<ServiceResponse<T>>();

        return new ServiceResponse<T> { Success = false, Message = await response.Content.ReadAsStringAsync() };
    }
}