namespace Health.WebApi.Endpoints;

public static class FileEndpoints
{
    private const long MaxFileSize = 20 * 1024 * 1024;
    private static readonly HashSet<string> AllowedExtensions = new(StringComparer.OrdinalIgnoreCase)
    {
        ".jpg", ".jpeg", ".png", ".webp", ".gif", ".pdf"
    };

    public static void MapFileEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("/api/files").RequireAuthorization();

        group.MapPost("/upload", async (HttpRequest request, CancellationToken ct) =>
        {
            if (!request.HasFormContentType)
                return Results.Ok(new { code = 40001, data = (object?)null, message = "需要 multipart/form-data" });

            var form = await request.ReadFormAsync(ct);
            var files = form.Files;
            if (files.Count == 0)
                return Results.Ok(new { code = 40001, data = (object?)null, message = "未上传文件" });

            var results = new List<object>();
            var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
            Directory.CreateDirectory(uploadsDir);

            foreach (var file in files)
            {
                if (file.Length <= 0)
                    continue;

                if (file.Length > MaxFileSize)
                    return Results.Ok(new { code = 40001, data = (object?)null, message = "文件大小不能超过 20MB" });

                var fileId = Guid.NewGuid().ToString();
                var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!AllowedExtensions.Contains(ext))
                    return Results.Ok(new { code = 40001, data = (object?)null, message = "不支持的文件类型" });

                var storedName = $"{fileId}{ext}";
                var filePath = Path.Combine(uploadsDir, $"{fileId}{ext}");
                await using var stream = new FileStream(filePath, FileMode.Create);
                await file.CopyToAsync(stream, ct);
                results.Add(new
                {
                    id = fileId,
                    name = file.FileName,
                    size = file.Length,
                    url = $"/uploads/{storedName}",
                    contentType = string.IsNullOrWhiteSpace(file.ContentType) ? "application/octet-stream" : file.ContentType
                });
            }

            return Results.Ok(new { code = 0, data = results, message = (string?)null });
        });
    }
}
