using Health.Application.Reports;

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, IReportService reports, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var data = await reports.GetReportsAsync(userId, ct);
            return Results.Ok(new { code = 0, data, message = (string?)null });
        });

        group.MapGet("/{id:guid}", async (Guid id, HttpContext http, IReportService reports, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var report = await reports.GetReportAsync(userId, id, ct);
            return report == null
                ? Results.Ok(new { code = 40004, data = (object?)null, message = "不存在" })
                : Results.Ok(new { code = 0, data = report, message = (string?)null });
        });

        group.MapPost("/", async (HttpContext http, IReportService reports, CancellationToken ct) =>
        {
            var userId = GetUserId(http);

            if (!http.Request.HasFormContentType)
                return Results.Ok(new { code = 400, data = (object?)null, message = "需要 multipart/form-data" });

            var form = await http.Request.ReadFormAsync(ct);
            var file = form.Files.GetFile("file");
            if (file == null)
                return Results.Ok(new { code = 400, data = (object?)null, message = "未上传文件" });

            await using var stream = file.OpenReadStream();
            var result = await reports.UploadReportAsync(
                userId,
                new ReportUploadFile(file.FileName, file.Length, stream),
                ct);

            return Results.Ok(new { code = result.Code, data = result.Report, message = result.Message });
        });

        group.MapPost("/{id:guid}/reanalyze", async (Guid id, HttpContext http, IReportService reports, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var ok = await reports.ReanalyzeReportAsync(userId, id, ct);
            return ok
                ? Results.Ok(new { code = 0, data = new { success = true }, message = "已重新提交 AI 分析" })
                : Results.Ok(new { code = 40004, data = (object?)null, message = "报告不存在或原始文件丢失" });
        });

        group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, IReportService reports, CancellationToken ct) =>
        {
            var userId = GetUserId(http);
            var ok = await reports.DeleteReportAsync(userId, id, ct);
            return ok
                ? Results.Ok(new { code = 0, data = new { success = true }, message = "已删除" })
                : Results.Ok(new { code = 40004, data = (object?)null, message = "不存在" });
        });
    }

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