using AutoMapper;
using DocumentOperator.Application.Common.DTOs;
using DocumentOperator.Application.Common.Interfaces;
using MediatR;

namespace DocumentOperator.Application.SwissQrCode.Queries;

/// <summary>
/// Query for extracting Swiss QR Code from PDF (Stream-based)
/// </summary>
public record ExtractSwissQrCodeQuery : IRequest<SwissQrCodeExtractionResult>
{
    /// <summary>
    /// PDF as stream (caller is responsible for disposal)
    /// </summary>
    public required Stream PdfStream { get; init; }
}

/// <summary>
/// Handler for ExtractSwissQrCodeQuery
/// Orchestrates Swiss QR Code extraction using ISwissQrCodeProcessor and AutoMapper
/// </summary>
public class ExtractSwissQrCodeQueryHandler(ISwissQrCodeProcessor qrCodeProcessor, IMapper mapper) 
    : IRequestHandler<ExtractSwissQrCodeQuery, SwissQrCodeExtractionResult>
{
    /// <summary>
    /// Extracts and parses Swiss QR Code from the PDF (default: scans all pages starting with last)
    /// Returns both parsed Bill DTO and raw QR text lines
    /// </summary>
    public async Task<SwissQrCodeExtractionResult> Handle(ExtractSwissQrCodeQuery request, CancellationToken cancellationToken)
    {
        // Extract: returns (Bill, RawLines) - pass stream directly
        var (bill, rawLines) = await qrCodeProcessor.ExtractSwissQrCodeAsync(request.PdfStream, pageNumbers: null, cancellationToken);

        // Map Codecrete Bill to DTO using AutoMapper
        var billDto = mapper.Map<SwissQrBillDto>(bill);

        // Return references (passed through) + Bill DTO + raw lines
        return new SwissQrCodeExtractionResult(
            Bill: billDto,
            RawLines: rawLines
        );
    }
}
