<?php

declare(strict_types=1);

namespace App\Service\Export\Encoder;

use App\Enum\Export\ExportFormatEnum;
use App\Service\Utils\FileUtils;
use Phpdocx\Create\CreateDocx;

/**
 * Encode HTML to docx format.
 */
class DocXEncoder implements EncoderInterface
{
    public function __construct(
        private readonly CreateDocx $phpDocx,
        private readonly FileUtils $fileUtils,
    ) {
    }

    public function support(string $format): bool
    {
        return $format === ExportFormatEnum::DOCX->value;
    }

    //  TODO: resolve Phpstan errors

    /**
     * Encode the given HTML content into docX, and
     * return the encoded content.
     *
     * @param array<string, mixed> $options
     *
     * @throws \Throwable
     */
    public function encode(string $html, array $options = []): string
    {
        $tempFilename = $this->fileUtils->getTempFilename('docx');

        // @see https://www.phpdocx.com/documentation/introduction/html-to-word-PHP#
        $this->phpDocx->embedHTML($html);

        try {
            $this->phpDocx->createDocx($tempFilename);

            return $this->fileUtils->getFileContent($tempFilename);
        } finally {
            $this->fileUtils->rmIfExist($tempFilename);
        }
    }
}
