namespace Health.WebApi.Endpoints;

public static class ReportEndpoints
{
    public static void MapReportEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/reports").RequireAuthorization();

        group.MapGet("/", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var reports = await db.Reports.Where(r => r.UserId == userId).OrderByDescending(r => r.CreatedAt).ToListAsync(ct);
            return Results.Ok(new { code = 0, data = reports, message = (string?)null });
        });

        group.MapGet("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var report = await db.Reports.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
            return report == null ? Results.Ok(new { code = 40004, message = "不存在" }) : Results.Ok(new { code = 0, data = report, message = (string?)null });
        });

        group.MapPost("/", async (CreateReportRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var report = new Report
            {
                Id = Guid.NewGuid(), UserId = userId,
                FileUrl = req.FileUrl, FileType = req.FileType,
                Category = req.Category ?? ReportCategory.Other,
                Status = ReportStatus.PendingDoctor,
                CreatedAt = DateTime.UtcNow,
            };
            db.Reports.Add(report);
            await db.SaveChangesAsync(ct);
            return Results.Ok(new { code = 0, data = new { report.Id }, 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;
}

public sealed record CreateReportRequest(string FileUrl, ReportFileType FileType, ReportCategory? Category);
