using FreeTubeSync.Model; namespace FreeTubeSync.EndPoints; public static class ProfileEndpoint { public static void MapProfileEndpoints(this WebApplication app) { var group = app.MapGroup("profile"); group.MapGet("/", GetAllProfiles); group.MapGet("/{id}", GetProfile); group.MapPost("/", UpdateProfile); group.MapDelete("/{id}", DeleteProfile); } private static async Task GetAllProfiles(IRepository repository, CancellationToken ct) { var results = await repository.GetAllAsync(ct); return Results.Ok(results); } private static async Task GetProfile(IRepository repository, string id, CancellationToken ct) { var result = await repository.GetByIdAsync(id, ct); return result == null ? Results.NotFound() : Results.Ok(result); } private static async Task UpdateProfile(IRepository repository, Profile profile, CancellationToken ct, ILogger logger) { var res = await repository.GetByIdAsync(profile._id, ct); if (res == null) { try { logger.LogInformation("Profile {id} does not exist, adding it to the database", profile._id); await repository.AddAsync(profile, ct); } catch (Exception) { logger.LogError("Failed to create profile {json}", profile._id); return Results.StatusCode(500); } } else { logger.LogInformation("Profile {id} exists, updating the database.", profile._id); res.UpdateFrom(profile); var toRemove = res.subscriptions.Where(sub => !profile.subscriptions.Any(x => x.id == sub.id)).ToList(); foreach (var sub in toRemove) res.subscriptions.Remove(sub); foreach (var sub in profile.subscriptions) { var osub = res.subscriptions.FirstOrDefault(x => x.id == sub.id); if (osub == null) res.subscriptions.Add(sub); else { osub.name = sub.name; osub.thumbnail = sub.thumbnail; } } await repository.UpdateAsync(res, ct); } return Results.Ok(); } private static async Task DeleteProfile(IRepository repository, string id, CancellationToken ct) { var result = await repository.GetByIdAsync(id, ct); if (result == null) return Results.NotFound(); await repository.DeleteAsync(result, ct); return Results.Ok(); } }