using DeliveryWebApi.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Internal; var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // storage setup // either use in-memory storage or postgres depending on cfg builder.Services.AddDbContext(options => { if (builder.Configuration.GetValue("UseInMemoryDatabase")) options.UseInMemoryDatabase("Delivery"); else { var connectionString = builder.Configuration.GetConnectionString("DatabaseConnection"); options.UseNpgsql(connectionString); } }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { // swagger setup app.UseSwagger(); app.UseSwaggerUI(); // migrate model to seed random test values for developers app.Services.CreateScope().ServiceProvider.GetRequiredService().Database.EnsureCreated(); } app.UseHttpsRedirection(); app.MapPut("/addDistrict", (DeliveryDbContext context, string name) => { if (context.Districts.Any(d => d.Name == name)) return Results.BadRequest(new { Error = "District with the same name already exists" }); var district = new District{ Name = name }; context.Districts.Add(district); var updated = context.SaveChanges(); if (updated <= 0) return Results.Json(new { Error = "Something went wrong while adding a new district" }, statusCode: 500); return Results.Ok(new { district.Id }); }); app.MapGet("/getDistrict/{id:long}", (DeliveryDbContext context, long id) => { var district = context.Districts.FirstOrDefault(d => d.Id == id); if (district == null) return Results.NotFound(new { Error = "District with the given id does not exist" }); return Results.Ok(new { district.Id, district.Name }); }); app.MapPut("/addOrder", (DeliveryDbContext context, long districtId, float weight, DateTime deliveryDate) => { var order = new Order{ DistrictId = districtId, Weight = weight, DeliveryDate = deliveryDate }; context.Orders.Add(order); var updated = context.SaveChanges(); if (updated <= 0) return Results.Json(new { Error = "Something went wrong while adding a new order" }, statusCode: 500); return Results.Ok(new { order.Id }); }); app.MapGet("/getOrder/{id:long}", (DeliveryDbContext context, long id) => { var order = context.Orders.FirstOrDefault(o => o.Id == id); if (order == null) return Results.NotFound(new { Error = "Order with the given id does not exist" }); return Results.Ok(new { order.Id, order.DistrictId, order.Weight, order.DeliveryDate }); }); app.MapGet("/getOrders", (DeliveryDbContext context, string? districtName, DateTime? firstDeliveryDate) => { var orders = context.Districts .Where(d => districtName == null || d.Name == districtName) .SelectMany(d => d.Orders) .Where(o => firstDeliveryDate == null || o.DeliveryDate >= firstDeliveryDate) .OrderBy(o => o.DeliveryDate) .Select(o => new { o.Id, o.District.Name, o.DeliveryDate, o.Weight }); return Results.Ok(orders); }); app.Run();