using System.Net; using FluentValidation; using Prefab.Domain.Exceptions; using Prefab.Endpoints; using Prefab.Web.Client.Models; using Prefab.Web.Client.Models.Shared; using Prefab.Web.Client.Pages; using Prefab.Web.Client.Services; namespace Prefab.Web.Gateway; public static class Categories { public class Endpoints : IEndpointRegistrar { public void MapEndpoints(IEndpointRouteBuilder endpoints) { endpoints.MapGet("/bff/categories/page", async (ICategoriesPageService service, CancellationToken cancellationToken) => { var result = await service.GetPage(cancellationToken); var status = result.Problem?.StatusCode ?? (result.IsSuccess ? StatusCodes.Status200OK : StatusCodes.Status500InternalServerError); return Results.Json(result, statusCode: status); }) .WithTags(nameof(Categories)); } } public class PageService(Prefab.Shared.Catalog.IModuleClient moduleClient) : ICategoriesPageService { public async Task> GetPage(CancellationToken cancellationToken) { try { var response = await moduleClient.Category.GetCategories(cancellationToken); var model = new CategoriesPageModel { Categories = response.Categories.Select(x => new CategoryListItemModel { Id = x.Id, Name = x.Name, ParentName = x.ParentName }) }; return Result.Success(model); } catch (Exception exception) { var problem = exception switch { ValidationException validationException => ResultProblem.FromValidation(validationException), DomainException domainException => ResultProblem.Unexpected(domainException.Message, domainException, HttpStatusCode.UnprocessableEntity), _ => ResultProblem.Unexpected("Failed to retrieve categories.", exception) }; return Result.Failure(problem); } } } }