using BudgetApp.PublicModels;
using BudgetApp.Services;
using Microsoft.AspNetCore.Mvc;
namespace BudgetApp.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UploadController(IUploadService uploadService) : ControllerBase
{
private readonly IUploadService _uploadService = uploadService ?? throw new ArgumentNullException(nameof(uploadService));
// Adjust as needed (e.g., 50 MB)
private const long MaxFileSizeBytes = 50 * 1024 * 1024;
///
/// Receives a CSV file via multipart/form-data.
///
[HttpPost("csv")]
[RequestSizeLimit(MaxFileSizeBytes)]
[Consumes("multipart/form-data")]
public async Task> UploadCsv([FromForm] IFormFile file, CancellationToken ct)
{
if (file is null)
return BadRequest("Missing 'file' form field.");
if (file.Length == 0)
return BadRequest("The uploaded file is empty.");
if (file.Length > MaxFileSizeBytes)
return BadRequest($"File too large. Limit is {MaxFileSizeBytes} bytes.");
// Light validation – content types for CSV vary by client/OS
var allowedContentTypes = new[]
{
"text/csv",
"application/csv",
"text/plain",
"application/vnd.ms-excel"
};
var hasCsvLikeContentType = allowedContentTypes.Contains(file.ContentType, StringComparer.OrdinalIgnoreCase);
var hasCsvExtension = Path.GetExtension(file.FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase);
if (!hasCsvLikeContentType && !hasCsvExtension)
return BadRequest("Only CSV files are accepted.");
var response = await _uploadService.UploadCsv(file, ct);
// Return whatever metadata/result you need
return Ok(response);
}
}
}