using OnProfNext.Shared.Models;
using System.Net.Http.Json;

namespace OnProfNext.Client.Services
{
    public class UserApiService
    {
        private readonly HttpClient _httpClient;

        public UserApiService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<(bool Success, List<User>? Data, string? Error)> GetUsersAsync()
        {
            try
            {
                var users = await _httpClient.GetFromJsonAsync<List<User>>("api/users");
                return (true, users ?? new List<User>(), null);
            }
            catch (HttpRequestException ex)
            {
                return (false, null, "Keine Verbindung zum Server. Bitte später erneut versuchen.");
            }
            catch (Exception ex)
            {
                return(false, null, $"Unerwarteter Fehler: {ex.Message}"); 
            }
        }

        public async Task<(bool Success, string? Error)> CreateUserAsync(User user)
        {
            try
            {
                var response = await _httpClient.PostAsJsonAsync("api/users", user);
                if (!response.IsSuccessStatusCode)
                {
                    return (false, $"Fehler beim Anlegen: {response.ReasonPhrase}"); 
                }

                return (true, null);
            }
            catch (HttpRequestException)
            {
                return (false, "Server nicht erreichbar.");
            }
        }


        public async Task<(bool Success, string? Error)> UpdateUserAsync(User user)
        {
            try
            {
                var response = await _httpClient.PutAsJsonAsync($"api/users/{user.Id}", user);

                if(!response.IsSuccessStatusCode)
                {
                    return (false, $"Fehler beim Aktualisieren: {response.ReasonPhrase}");
                }
                return (true, null);
            }

            catch (HttpRequestException)
            {
                return (false, "Server nicht erreichbar.");
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }

        public async Task<(bool Success, string? Error)> DeleteUserAsync(int userId)
        {
            try
            {
                var response = await _httpClient.DeleteAsync($"api/users/{userId}");
                if (!response.IsSuccessStatusCode)
                {
                    return (false, $"Fehler beim Löschen: {response.ReasonPhrase}");
                }
                return (true, null);
            }
            catch (HttpRequestException)
            {
                return (false, "Server nicht erreichbar.");
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }
    }
}
