using DocumentOperator.Application.Common.DTOs;
using DocumentOperator.Application.ValidatePdf.Queries;
using DocumentOperator.Application.ValidatePdfA.Queries;
using DocumentOperator.Domain.Common.Exceptions;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace DocumentOperator.API.Controllers;

/// <summary>
/// PDF validation operations
/// </summary>
[ApiController]
[Route("api/pdf/validation")]
[Produces("application/json")]
public class PdfValidationController(IMediator Mediator) : ControllerBase
{
    /// <summary>
    /// Validates a PDF document and returns metadata (multipart/form-data)
    /// </summary>
    /// <param name="file">PDF file to validate</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>PDF metadata (page count, file size, PDF version, attachments)</returns>
    /// <response code="200">PDF is valid, metadata returned</response>
    /// <response code="400">Invalid PDF or file format</response>
    /// <response code="500">Internal server error during validation</response>
    [HttpPost("validate")]
    [Consumes("multipart/form-data")]
    [ProducesResponseType(typeof(PdfValidationResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ValidateFromFile(
        IFormFile file,
        CancellationToken cancellationToken)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest(new ProblemDetails
            {
                Title = "Invalid file",
                Detail = "File is required and cannot be empty",
                Status = StatusCodes.Status400BadRequest
            });
        }

        // Use IFormFile stream directly (no intermediate byte[] conversion)
        using var pdfStream = file.OpenReadStream();
        
        // Direct pass-through to MediatR
        var query = new ValidatePdfQuery { PdfStream = pdfStream };
        var result = await Mediator.Send(query, cancellationToken);
        
        return Ok(result);
    }

    /// <summary>
    /// Validates a PDF document and returns metadata (Base64 JSON)
    /// </summary>
    /// <param name="request">Request containing Base64-encoded PDF</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>PDF metadata (page count, file size, PDF version, attachments)</returns>
    /// <response code="200">PDF is valid, metadata returned</response>
    /// <response code="400">Invalid PDF or Base64 format</response>
    /// <response code="500">Internal server error during validation</response>
    [HttpPost("validate")]
    [Consumes("application/json")]
    [ProducesResponseType(typeof(PdfValidationResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ValidateFromBase64(
        [FromBody] ValidatePdfBase64Request 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);
        
        // Direct pass-through to MediatR
        var query = new ValidatePdfQuery { PdfStream = pdfStream };
        var result = await Mediator.Send(query, cancellationToken);
        
        return Ok(result);
    }

    /// <summary>
    /// Validates a PDF/A document and checks conformance level (multipart/form-data)
    /// </summary>
    /// <param name="file">PDF file to validate</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>PDF/A metadata (conformance level, errors, warnings)</returns>
    /// <response code="200">PDF/A validation completed, results returned</response>
    /// <response code="400">Invalid PDF or file format</response>
    /// <response code="500">Internal server error during validation</response>
    [HttpPost("validate-pdfa")]
    [Consumes("multipart/form-data")]
    [ProducesResponseType(typeof(PdfAValidationResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ValidatePdfAFromFile(
        IFormFile file,
        CancellationToken cancellationToken)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest(new ProblemDetails
            {
                Title = "Invalid file",
                Detail = "File is required and cannot be empty",
                Status = StatusCodes.Status400BadRequest
            });
        }

        // Use IFormFile stream directly (no intermediate byte[] conversion)
        using var pdfStream = file.OpenReadStream();
        
        // Direct pass-through to MediatR
        var query = new ValidatePdfAQuery { PdfStream = pdfStream };
        var result = await Mediator.Send(query, cancellationToken);
        
        return Ok(result);
    }

    /// <summary>
    /// Validates a PDF/A document and checks conformance level (Base64 JSON)
    /// </summary>
    /// <param name="request">Request containing Base64-encoded PDF</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>PDF/A metadata (conformance level, errors, warnings)</returns>
    /// <response code="200">PDF/A validation completed, results returned</response>
    /// <response code="400">Invalid PDF or Base64 format</response>
    /// <response code="500">Internal server error during validation</response>
    [HttpPost("validate-pdfa")]
    [Consumes("application/json")]
    [ProducesResponseType(typeof(PdfAValidationResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ValidatePdfAFromBase64(
        [FromBody] ValidatePdfABase64Request 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);
        
        // Direct pass-through to MediatR
        var query = new ValidatePdfAQuery { PdfStream = pdfStream };
        var result = await Mediator.Send(query, cancellationToken);
        
        return Ok(result);
    }
}

/// <summary>
/// Request DTO for Base64-encoded PDF validation
/// </summary>
public record ValidatePdfBase64Request
{
    /// <summary>
    /// PDF document encoded as Base64 string
    /// </summary>
    /// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
    public string Base64Pdf { get; init; } = string.Empty;
}

/// <summary>
/// Request DTO for Base64-encoded PDF/A validation
/// </summary>
public record ValidatePdfABase64Request
{
    /// <summary>
    /// PDF document encoded as Base64 string
    /// </summary>
    /// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
    public string Base64Pdf { get; init; } = string.Empty;
}
