using DocumentService.Application.AddAttachments; using DocumentService.Application.CheckPdfAttachments.Queries; using DocumentService.Application.Common.DTOs; using DocumentService.Application.ExtractPdfAttachments; using DocumentService.Client.Models.Requests; using DocumentService.Domain.Common.Exceptions; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DocumentService.API.Controllers; /// /// Controller for PDF attachment operations (detection, extraction, embedding) /// [ApiController] [Route("api/pdf/attachments")] [Produces("application/json")] public class PdfAttachmentController(IMediator mediator) : ControllerBase { /// /// Checks if a PDF contains embedded files (attachments) and returns their metadata. /// Supports multipart/form-data file upload. /// /// The PDF file to check for attachments /// Cancellation token /// Attachment check result with metadata for all found attachments /// PDF successfully checked - returns attachment details /// Invalid input (file missing, not a PDF, or corrupted) /// Internal server error during PDF processing [HttpPost("check")] [Consumes("multipart/form-data")] [ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task CheckAttachmentsFromFile( IFormFile file, CancellationToken cancellationToken) { // Use IFormFile stream directly (no intermediate byte[] conversion) using var pdfStream = file.OpenReadStream(); // Send query to MediatR (ValidationBehavior runs automatically) var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream }; var result = await mediator.Send(query, cancellationToken); return Ok(result); } /// /// Checks if a PDF contains embedded files (attachments) and returns their metadata. /// Supports Base64-encoded PDF via JSON payload. /// /// Request containing Base64-encoded PDF /// Cancellation token /// Attachment check result with metadata for all found attachments /// PDF successfully checked - returns attachment details /// Invalid input (Base64 format error, not a PDF, or corrupted) /// Internal server error during PDF processing [HttpPost("check")] [Consumes("application/json")] [ProducesResponseType(typeof(AttachmentCheckResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task CheckAttachmentsFromBase64( [FromBody] CheckPdfAttachmentsRequest request, CancellationToken cancellationToken) { // Convert Base64 to stream (wrap in try-catch to throw BadRequestException) byte[] pdfBytes; try { pdfBytes = Convert.FromBase64String(request.Base64Pdf); } catch (FormatException ex) { throw new BadRequestException("Invalid Base64 format: " + ex.Message); } using var pdfStream = new MemoryStream(pdfBytes); // Send query to MediatR (ValidationBehavior runs automatically) var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream }; var result = await mediator.Send(query, cancellationToken); return Ok(result); } /// /// Extracts all embedded files from a PDF and returns them as a ZIP archive. /// Supports multipart/form-data file upload. /// /// The PDF file to extract attachments from /// Cancellation token /// ZIP archive containing all extracted attachments /// Attachments extracted successfully - returns ZIP file /// Invalid input (file missing, not a PDF, or corrupted) /// PDF contains no attachments /// Internal server error during PDF processing [HttpPost("extract")] [Consumes("multipart/form-data")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task ExtractAttachmentsFromFile( IFormFile file, CancellationToken cancellationToken) { // Use IFormFile stream directly (no intermediate byte[] conversion) using var pdfStream = file.OpenReadStream(); // Send command to MediatR var command = new ExtractPdfAttachmentsCommand { PdfStream = pdfStream }; byte[] zipBytes = await mediator.Send(command, cancellationToken); // Return ZIP file return File(zipBytes, "application/zip", "attachments.zip"); } /// /// Extracts all embedded files from a PDF and returns them as a ZIP archive. /// Supports Base64-encoded PDF via JSON payload. /// /// Request containing Base64-encoded PDF /// Cancellation token /// ZIP archive containing all extracted attachments /// Attachments extracted successfully - returns ZIP file /// Invalid input (Base64 format error, not a PDF, or corrupted) /// PDF contains no attachments /// Internal server error during PDF processing [HttpPost("extract")] [Consumes("application/json")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task ExtractAttachmentsFromBase64( [FromBody] ExtractPdfAttachmentsRequest request, CancellationToken cancellationToken) { // Convert Base64 to stream (wrap in try-catch to throw BadRequestException) byte[] pdfBytes; try { pdfBytes = Convert.FromBase64String(request.Base64Pdf); } catch (FormatException ex) { throw new BadRequestException("Invalid Base64 format: " + ex.Message); } using var pdfStream = new MemoryStream(pdfBytes); // Send command to MediatR var command = new ExtractPdfAttachmentsCommand { PdfStream = pdfStream }; byte[] zipBytes = await mediator.Send(command, cancellationToken); // Return ZIP file return File(zipBytes, "application/zip", "attachments.zip"); } /// /// Embeds one or more files as attachments in a PDF document (supports PDF/A-3). /// Supports multipart/form-data file upload. /// /// The PDF file to add attachments to /// Files to embed as attachments (one or more) /// Cancellation token /// PDF with embedded attachments /// Attachments added successfully - returns PDF /// Invalid input (file missing, not a PDF, or no attachments provided) /// Internal server error during PDF processing [Obsolete("This endpoint is not implemented yet.")] [HttpPost("add")] [Consumes("multipart/form-data")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task AddAttachmentsFromFile( IFormFile pdfFile, List attachmentFiles, CancellationToken cancellationToken) { if (pdfFile == null || pdfFile.Length == 0) { throw new BadRequestException("PDF file is required"); } if (attachmentFiles == null || attachmentFiles.Count == 0) { throw new BadRequestException("At least one attachment file is required"); } // Use IFormFile stream directly (no intermediate byte[] conversion) using var pdfStream = pdfFile.OpenReadStream(); // Convert attachment files to AttachmentFile records var attachments = new List(); foreach (var file in attachmentFiles) { using var ms = new MemoryStream(); await file.CopyToAsync(ms, cancellationToken); attachments.Add(new AttachmentFile { FileName = file.FileName, Content = ms.ToArray(), MimeType = file.ContentType }); } // Send command to MediatR var command = new AddAttachmentsCommand { PdfStream = pdfStream, Attachments = attachments }; byte[] resultPdf = await mediator.Send(command, cancellationToken); // Return PDF with attachments return File(resultPdf, "application/pdf", "with-attachments.pdf"); } /// /// Embeds one or more files as attachments in a PDF document (supports PDF/A-3). /// Supports Base64-encoded PDF and attachments via JSON payload. /// /// Request containing Base64-encoded PDF and attachments /// Cancellation token /// PDF with embedded attachments /// Attachments added successfully - returns PDF /// Invalid input (Base64 format error, not a PDF, or no attachments provided) /// Internal server error during PDF processing [Obsolete("This endpoint is not implemented yet.")] [HttpPost("add")] [Consumes("application/json")] [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task AddAttachmentsFromBase64( [FromBody] AddAttachmentsRequest request, CancellationToken cancellationToken) { // Convert Base64 PDF to stream byte[] pdfBytes; try { pdfBytes = Convert.FromBase64String(request.Base64Pdf); } catch (FormatException ex) { throw new BadRequestException("Invalid Base64 PDF format: " + ex.Message); } using var pdfStream = new MemoryStream(pdfBytes); // Convert Base64 attachments to AttachmentFile records var attachments = new List(); foreach (var att in request.Attachments) { byte[] attBytes; try { attBytes = Convert.FromBase64String(att.Base64Content); } catch (FormatException ex) { throw new BadRequestException($"Invalid Base64 format for attachment '{att.FileName}': " + ex.Message); } attachments.Add(new AttachmentFile { FileName = att.FileName, Content = attBytes, MimeType = att.MimeType }); } // Send command to MediatR var command = new AddAttachmentsCommand { PdfStream = pdfStream, Attachments = attachments }; byte[] resultPdf = await mediator.Send(command, cancellationToken); // Return PDF with attachments return File(resultPdf, "application/pdf", "with-attachments.pdf"); } } /// /// Request DTO for Base64-encoded PDF attachment check /// public record CheckPdfAttachmentsRequest { /// /// PDF document encoded as Base64 string /// /// JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c... public string Base64Pdf { get; init; } = string.Empty; } /// /// Request DTO for Base64-encoded PDF attachment extraction /// public record ExtractPdfAttachmentsRequest { /// /// PDF document encoded as Base64 string /// /// JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c... public required string Base64Pdf { get; init; } } /// /// Request DTO for Base64-encoded PDF with attachments to add /// public record AddAttachmentsRequest { /// /// PDF document encoded as Base64 string /// /// JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c... public required string Base64Pdf { get; init; } /// /// List of attachments to embed /// public required List Attachments { get; init; } } /// /// DTO for attachment file in request /// public record AttachmentRequestDto { /// /// File name (e.g., "invoice.xml", "document.pdf") /// /// factur-x.xml public required string FileName { get; init; } /// /// File content encoded as Base64 string /// /// PD94bWwgdmVyc2lvbj0iMS4wIj8+... public required string Base64Content { get; init; } /// /// MIME type (optional, e.g., "application/xml") /// /// application/xml public string? MimeType { get; init; } }