using Shared.DTOs;
using System.Net.Http.Json;

namespace Front.Services
{
    public class MidLevel
    {
        private readonly ILocalStorageService _localStorage;
        private readonly UserAuthenticationDTO _user;
        private readonly HttpClient _httpClient;
        public MidLevel(ILocalStorageService localStorage, UserAuthenticationDTO user, HttpClient httpClient)
        {
            _localStorage = localStorage;
            _user = user;
            _httpClient = httpClient;
        }
        public async Task InitAsync()
        {
            var token = await _localStorage.GetItem<string>("token");
            if (!string.IsNullOrEmpty(token))
            {
                _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var request = await _httpClient.GetAsync("User/CheckAuthenticate");
                if (request.IsSuccessStatusCode)
                {
                    var userinfomodel = await request.Content.ReadFromJsonAsync<UserAuthenticationDTO>();
                    _user.Token = token;
                    _user.Company = userinfomodel?.Company;
                    _user.FullName = userinfomodel.FullName;
                    _user.Photo = userinfomodel.Photo;
                    _user.exitDate = userinfomodel.exitDate;
                    _user.enterDate = userinfomodel.enterDate;
                    _user.UserName= userinfomodel.UserName;
                }
                else { _httpClient.DefaultRequestHeaders.Clear(); }
            }
               
        }
    }
}
