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

namespace DocumentOperator.API.Controllers;

/// <summary>
/// Swiss QR Code extraction operations
/// </summary>
[ApiController]
[Route("api/pdf/qr-code")]
[Produces("application/json")]
public class SwissQrCodeController(IMediator Mediator) : ControllerBase
{
    /// <summary>
    /// Extracts Swiss QR Code from the last page of a PDF document (multipart/form-data)
    /// </summary>
    /// <param name="file">PDF file containing Swiss QR Code</param>
    /// <param name="raw">If true, returns raw QR text lines instead of parsed Bill object</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns>
    /// <response code="200">Swiss QR Code extracted successfully</response>
    /// <response code="400">Invalid PDF or file format</response>
    /// <response code="404">No Swiss QR Code found on the last page</response>
    /// <response code="500">Internal server error during extraction</response>
    [HttpPost("extract-swiss")]
    [Consumes("multipart/form-data")]
    [ProducesResponseType(typeof(SwissQrCodeExtractionResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ExtractFromFile(
        IFormFile file,
        [FromQuery] bool raw = false,
        CancellationToken cancellationToken = default)
    {
        if (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 ExtractSwissQrCodeQuery 
        { 
            PdfStream = pdfStream
        };
        var result = await Mediator.Send(query, cancellationToken);

        return Ok(raw ? result.RawLines : result.Bill);
    }

    /// <summary>
    /// Extracts Swiss QR Code from the last page of a PDF document (Base64 JSON)
    /// </summary>
    /// <param name="request">Request containing Base64-encoded PDF</param>
    /// <param name="raw">If true, returns raw QR text lines instead of parsed Bill object</param>
    /// <param name="cancellationToken">Cancellation token</param>
    /// <returns>Swiss QR Code data (IBAN, amount, creditor, debtor, reference, etc.)</returns>
    /// <response code="200">Swiss QR Code extracted successfully</response>
    /// <response code="400">Invalid PDF or Base64 format</response>
    /// <response code="404">No Swiss QR Code found on the last page</response>
    /// <response code="500">Internal server error during extraction</response>
    [HttpPost("extract-swiss")]
    [Consumes("application/json")]
    [ProducesResponseType(typeof(SwissQrCodeExtractionResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ExtractFromBase64(
        [FromBody] ExtractSwissQrCodeBase64Request request,
        [FromQuery] bool raw = false,
        CancellationToken cancellationToken = default)
    {
        // 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 ExtractSwissQrCodeQuery { PdfStream = pdfStream };
        var result = await Mediator.Send(query, cancellationToken);

        return Ok(raw ? result.RawLines : result.Bill);
    }
}

/// <summary>
/// Request DTO for Base64-encoded Swiss QR Code extraction
/// </summary>
public record ExtractSwissQrCodeBase64Request
{
    /// <summary>
    /// PDF document encoded as Base64 string
    /// </summary>
    /// <example>JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9UeXBlL0NhdGFsb2c...</example>
    public required string Base64Pdf { get; init; }
}
