namespace Health.WebApi.Endpoints;

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

        group.MapPost("/upload", async (HttpRequest request) =>
        {
            var form = await request.ReadFormAsync();
            var files = form.Files;
            var results = new List<object>();
            var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
            Directory.CreateDirectory(uploadsDir);

            foreach (var file in files)
            {
                var fileId = Guid.NewGuid().ToString();
                var ext = Path.GetExtension(file.FileName);
                var filePath = Path.Combine(uploadsDir, $"{fileId}{ext}");
                using var stream = new FileStream(filePath, FileMode.Create);
                await file.CopyToAsync(stream);
                results.Add(new { id = fileId, name = file.FileName, size = file.Length });
            }

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