using iText.Kernel.Pdf;
using IWS5.Importer.Abstractions.Interfaces;
using Serilog.Context;
using ILogger = Serilog.ILogger;

namespace IWS5.Importer.Worker.Validation;

public class DocumentValidator : IDocumentValidator
{
    private readonly ILogger _logService;
    private readonly long _maxAllowedSizeInBytes;

    public DocumentValidator(ILogger logService, IGeneralImportSettingsProvider settingsProvider)
    {
        _logService = logService;
        _maxAllowedSizeInBytes = settingsProvider.Settings.MaxPdfSizeMB * 1024L * 1024L;
    }

    public bool ValidatePdf(string pdfFilePath)
    {
        using (LogContext.PushProperty("LogContext", nameof(DocumentValidator)))
        {
            if (!File.Exists(pdfFilePath))
            {
                _logService.Error("PDF file not found: {FilePath}", pdfFilePath);
                return false;
            }

            FileInfo fileInfo = new(pdfFilePath);

            if (fileInfo.Length == 0)
            {
                _logService.Error("PDF file has zero length: {FilePath}", pdfFilePath);
                return false;
            }

            if (fileInfo.Length > _maxAllowedSizeInBytes)
            {
                _logService.Error("PDF file size exceeds limit ({FileSize} bytes): {FilePath}", fileInfo.Length, pdfFilePath);
                return false;
            }

            try
            {
                using var pdfReader = new PdfReader(pdfFilePath);
                using var pdfDocument = new PdfDocument(pdfReader);

                if (pdfDocument.GetNumberOfPages() == 0)
                {
                    _logService.Error("PDF file has no pages: {FilePath}", pdfFilePath);
                    return false;
                }
            }
            catch (iText.Kernel.Exceptions.BadPasswordException)
            {
                _logService.Error("PDF file is encrypted/protected: {FilePath}", pdfFilePath);
                return false;
            }
            catch (Exception ex)
            {
                _logService.Error(ex, "Exception while validating PDF file: {FilePath}", pdfFilePath);
                return false;
            }
        }

        return true;
    }
}
