namespace Health.WebApi.Endpoints;

public static class DietEndpoints
{
    public static void MapDietEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/diet-records").RequireAuthorization();

        group.MapGet("/", async (string? date, string? mealType, HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var query = db.DietRecords.Include(d => d.FoodItems).Where(d => d.UserId == userId);
            if (DateOnly.TryParse(date, out var d)) query = query.Where(r => r.RecordedAt == d);
            if (Enum.TryParse<MealType>(mealType, ignoreCase: true, out var mt)) query = query.Where(r => r.MealType == mt);
            var records = await query.OrderByDescending(r => r.RecordedAt).Select(r => new
            {
                r.Id, MealType = r.MealType.ToString(), r.TotalCalories, r.HealthScore, r.RecordedAt,
                foodItems = r.FoodItems.Select(f => new { f.Name, f.Portion, f.Calories })
            }).ToListAsync(ct);
            return Results.Ok(new { code = 0, data = records, message = (string?)null });
        });

        group.MapPost("/", async (HttpRequest request, HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            request.EnableBuffering();
            using var reader = new StreamReader(request.Body);
            var body = await reader.ReadToEndAsync(ct);
            request.Body.Position = 0;
            using var json = JsonDocument.Parse(body);
            var root = json.RootElement;
            var record = new DietRecord
            {
                Id = Guid.NewGuid(), UserId = userId,
                MealType = Enum.TryParse<MealType>(root.TryGetProperty("mealType", out var mt) ? mt.GetString() : "Lunch", out var meal) ? meal : MealType.Lunch,
                TotalCalories = root.TryGetProperty("totalCalories", out var tc) ? tc.GetInt32() : null,
                HealthScore = root.TryGetProperty("healthScore", out var hs) ? hs.GetInt32() : null,
                RecordedAt = root.TryGetProperty("recordedAt", out var ra) && DateOnly.TryParse(ra.GetString(), out var d) ? d : DateOnly.FromDateTime(DateTime.Now),
            };
            if (root.TryGetProperty("foodItems", out var items))
            {
                var i = 0;
                foreach (var fi in items.EnumerateArray())
                {
                    record.FoodItems.Add(new DietFoodItem
                    {
                        Id = Guid.NewGuid(), Name = fi.TryGetProperty("name", out var n) ? n.GetString()! : "",
                        Portion = fi.TryGetProperty("portion", out var p) ? p.GetString() : null,
                        Calories = fi.TryGetProperty("calories", out var c) ? c.GetInt32() : null,
                        SortOrder = fi.TryGetProperty("sortOrder", out var so) ? so.GetInt32() : i,
                    });
                    i++;
                }
            }
            db.DietRecords.Add(record);
            await db.SaveChangesAsync(ct);
            return Results.Ok(new { code = 0, data = new { record.Id }, message = (string?)null });
        });

        group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var record = await db.DietRecords.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
            if (record != null) { db.DietRecords.Remove(record); await db.SaveChangesAsync(ct); }
            return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
        });
    }

    private static Guid GetUserId(HttpContext http) =>
        Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
}

