using IWS5.Server.Enums;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIORenderer;

namespace IWS5.Server.Utils.Converter.TiffConverter;

internal class WordFileToTiffConverter : IFileConverter
{
    private static readonly HashSet<string> Extensions = new(StringComparer.OrdinalIgnoreCase)
    {
        nameof(ConvertibleFileTypes.doc).ToLowerInvariant(),
        nameof(ConvertibleFileTypes.docx).ToLowerInvariant(),
    };

    public bool CanConvert(string sourceFileExtension, string targetFileExtension) => Extensions.Contains(sourceFileExtension) && 
        string.Equals(targetFileExtension, nameof(ConvertibleFileTypes.tiff), StringComparison.OrdinalIgnoreCase);

    public async Task<byte[]> ConvertAsync(byte[] inputFile)
    {
        try
        {
            using var docStream = new MemoryStream(inputFile);
            using var wordDocument = new WordDocument(docStream, FormatType.Automatic);
            using var renderer = new DocIORenderer();

            using var pdfDocument = renderer.ConvertToPDF(wordDocument);
            using var pdfStream = new MemoryStream();

            pdfDocument.Save(pdfStream);
            pdfDocument.Close(true);

            return await PdfToTiffConverter.ConvertAsync(pdfStream.ToArray());
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Error converting Word document to TIFF: {ex.Message}", ex);
        }
    }
}