using Butter.Dtos.User;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.Extensions.Options;
using System.Net;

namespace MilkStream.Services;

public class UserServiceOptions {
    public string BaseUrl { get; set; } = string.Empty;
}

public class UserService {
    HttpClient   client;
    LoginService loginService;

    public UserService(IOptions<UserServiceOptions> options, LoginService loginService, IHttpClientFactory httpClientFactory) {
        client             = httpClientFactory.CreateClient("MilkstreamClient");
        client.BaseAddress = new(options.Value.BaseUrl);
        this.loginService  = loginService;
    }

    public async Task<UserInfoDto?> GetUserAsync() {
        var auth = await loginService.RetrieveAuthInfo();
        if (loginService.authInfo == null || !auth) return null;
        
        client.DefaultRequestHeaders.Authorization = new("bearer", loginService.authInfo.Token);
        HttpResponseMessage response = await client.GetAsync($"api/user/{loginService.authInfo.UserId}").ConfigureAwait(false);

        if (response.IsSuccessStatusCode) return (await response.Content.ReadFromJsonAsync<UserInfoDto>())!;
        
        return null;
    }
}
