using System.Diagnostics; using System.Net; 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 CountRequestResult(uint Value); public async Task<(uint, List)> ListUsers(uint from, uint len, string? searchString = null) { var httpResponse = await Client.GetAsync($"/admin/users?start={from}&n={len}&search={searchString ?? ""}"); await ErrorsUtils.EnsureResponseIsOk(httpResponse); var users = await httpResponse.Content.ReadFromJsonAsync>() ?? throw new Exception("Received non-parseable json from server"); var search = searchString != null ? $"&search={searchString}" : ""; httpResponse = await Client.GetAsync($"/admin/users/count{search}"); await ErrorsUtils.EnsureResponseIsOk(httpResponse); var count = await httpResponse.Content.ReadFromJsonAsync(); return (count!.Value, users); } private record AddUserRequestDto(string Username, string Email, string Password, bool IsAdmin); private record AddUserResponseDto(uint Id); public async Task AddUser(string username, string email, string password, bool isAdmin) { var httpResponse = await Client.PostAsJsonAsync("/admin/users", new AddUserRequestDto(username, email, password, isAdmin)); await ErrorsUtils.EnsureResponseIsOk(httpResponse); 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 RemoveUsersRequestDto(uint[] Identifiers); public async Task RemoveUsers(IEnumerable userIds) { var httpResponse = await Client.PostAsJsonAsync("/admin/users/remove-all", new RemoveUsersRequestDto(userIds.ToArray())); await ErrorsUtils.EnsureResponseIsOk(httpResponse); } private record UpdateUserRequestDto(string Email, string Username, bool IsAdmin); public async Task UpdateUser(User user) { var httpResponse = await Client.PutAsJsonAsync($"/admin/users/{user.Id}", new UpdateUserRequestDto(user.Email, user.Name, user.IsAdmin)); await ErrorsUtils.EnsureResponseIsOk(httpResponse); } }