using Microsoft.EntityFrameworkCore; using YesChef.Api.Auth; using YesChef.Api.Data; using YesChef.Api.Entities; namespace YesChef.Api.Features.Stores; public static class StoreEndpoints { public record CreateStoreRequest(string Name, int SortOrder = 0); public record UpdateStoreRequest(string Name, int SortOrder); public static RouteGroupBuilder MapStoreEndpoints(this RouteGroupBuilder group) { group.MapGet("/", async (YesChefDb db, HttpContext http) => { var familyId = http.User.GetFamilyId(); return await db.Stores .Where(s => s.FamilyId == familyId) .OrderBy(s => s.SortOrder).ThenBy(s => s.Name) .ToListAsync(); }); group.MapPost("/", async (CreateStoreRequest request, YesChefDb db, HttpContext http) => { var store = new Store { FamilyId = http.User.GetFamilyId(), Name = request.Name, SortOrder = request.SortOrder, }; db.Stores.Add(store); await db.SaveChangesAsync(); return Results.Created($"/api/stores/{store.Id}", store); }); group.MapPut("/{id:int}", async (int id, UpdateStoreRequest request, YesChefDb db, HttpContext http) => { var familyId = http.User.GetFamilyId(); var store = await db.Stores.FirstOrDefaultAsync(s => s.Id == id && s.FamilyId == familyId); if (store is null) return Results.NotFound(); store.Name = request.Name; store.SortOrder = request.SortOrder; await db.SaveChangesAsync(); return Results.Ok(store); }); group.MapDelete("/{id:int}", async (int id, YesChefDb db, HttpContext http) => { var familyId = http.User.GetFamilyId(); var store = await db.Stores.FirstOrDefaultAsync(s => s.Id == id && s.FamilyId == familyId); if (store is null) return Results.NotFound(); var hasLists = await db.ShoppingLists.AnyAsync(l => l.StoreId == id && l.FamilyId == familyId); if (hasLists) return Results.BadRequest(new { error = "Store has shopping lists. Remove them first." }); db.Stores.Remove(store); await db.SaveChangesAsync(); return Results.NoContent(); }); return group; } }