using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Blazored.LocalStorage;

namespace HealthcareManagerUI.Services.TokenService;

public class TokenService : ITokenService
{
    private readonly ILocalStorageService _localStorage;
    private readonly HttpClient _httpClient;
    private const string TokenKey = "";

    public TokenService(ILocalStorageService localStorage, HttpClient httpClient)
    {
        _localStorage = localStorage;
        _httpClient = httpClient;
    }

    public async Task<string> GetTokenAsync()
    {
        return await _localStorage.GetItemAsStringAsync(TokenKey);
    }

    public async Task SaveTokenAsync(string token)
    {
        await _localStorage.SetItemAsStringAsync(TokenKey, token);
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    }

    public async Task RefreshTokenAsync()
    {
        var token = await GetTokenAsync();
        
        var jsonRequest = JsonSerializer.Serialize(new { token = token });
        var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
        
        var response = await _httpClient.PostAsync("http://localhost:5151/api/Authorization/refresh_token", content);
        if (response.IsSuccessStatusCode)
        {
            var newToken = await response.Content.ReadAsStringAsync();
            await SaveTokenAsync(newToken);
        }
    }
}