using System.Net.Http.Json; using AdminPanel.Models; namespace AdminPanel.Services; public class HttpUsersService : IUsersService { private HttpClient Client { get; } public HttpUsersService(HttpClient client) { this.Client = client; } private record ListUsersResponse(List Users, uint TotalCount); public async Task<(uint, List)> ListUsers(uint from, uint len, string? searchString = null) { var httpResponse = await Client.GetAsync($"/api/admin/list-users?start={from}&n={len}&search={searchString ?? ""}"); httpResponse.EnsureSuccessStatusCode(); var response = await httpResponse.Content.ReadFromJsonAsync() ?? throw new Exception("Received non-parseable json from server"); return (response.TotalCount, response.Users); } private record AddUserRequest(string Username, string Email, string Password, bool IsAdmin); private record AddUserResponse(uint Id); public async Task AddUser(string username, string email, string password, bool isAdmin) { var httpResponse = await Client.PostAsJsonAsync("/api/admin/user/add", new AddUserRequest(username, email, password, isAdmin)); httpResponse.EnsureSuccessStatusCode(); var response = await httpResponse.Content.ReadFromJsonAsync() ?? throw new Exception("Received non-parseable json from server"); return new User { Name = username, Email = email, IsAdmin = isAdmin, Id = response.Id }; } private record RemoveUsersRequest(uint[] Identifiers); public async Task RemoveUsers(IEnumerable userIds) { var httpResponse = await Client.PostAsJsonAsync("/api/admin/user/remove-all", new RemoveUsersRequest(userIds.ToArray())); httpResponse.EnsureSuccessStatusCode(); } private record UpdateUserRequest(string Email, string Username, bool IsAdmin); public async Task UpdateUser(User user) { var httpResponse = await Client.PostAsJsonAsync($"/api/admin/user/{user.Id}/update", new UpdateUserRequest(user.Email, user.Name, user.IsAdmin)); httpResponse.EnsureSuccessStatusCode(); } }