<?php

namespace Zab\ZabSite\Search;

use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\IndexedSearch\Dto\IndexingDataAsString;
use TYPO3\CMS\IndexedSearch\FileContentParser;

/**
 * Extends the default FileContentParser to:
 * - Use the filename as indexed title instead of PDF metadata title
 * - Index the entire PDF as a single document (no page splitting)
 * - Include sys_file_metadata alternative text and description in the indexed body
 */
class PdfFileContentParser extends FileContentParser
{
    public function readFileContent(string $ext, string $absFile, string|int $cPKey): IndexingDataAsString|false|null
    {
        $result = parent::readFileContent($ext, $absFile, $cPKey);

        if ($result !== null && $ext === 'pdf') {
            $result->title = PathUtility::basename($absFile);

            $metadata = $this->getFileMetadataForAbsPath($absFile);
            if ($metadata !== null) {
                $extra = implode(' ', array_filter([
                    $metadata['alternative'] ?? '',
                    $metadata['description'] ?? '',
                ]));
                if ($extra !== '') {
                    $result->body = trim($result->body . ' ' . $extra);
                }
            }
        }

        return $result;
    }

    /**
     * Looks up sys_file_metadata for the given absolute file path using FAL ResourceFactory.
     *
     * @return array{alternative: string, description: string}|null
     */
    protected function getFileMetadataForAbsPath(string $absFile): ?array
    {
        try {
            $resourceFactory = GeneralUtility::makeInstance(ResourceFactory::class);
            $file = $resourceFactory->retrieveFileOrFolderObject($absFile);
            if ($file === null) {
                return null;
            }
            $metadata = $file->getMetaData()->get();
            return [
                'alternative' => $metadata['alternative'] ?? '',
                'description' => $metadata['description'] ?? '',
            ];
        } catch (FileDoesNotExistException|\Exception $e) {
            return null;
        }
    }

    /**
     * Override to prevent PDF page splitting — returns [0] so the PDF
     * is indexed as a single document without page suffixes.
     */
    public function fileContentParts(string $ext, string $absFile): array
    {
        if ($ext === 'pdf') {
            return [0];
        }

        return parent::fileContentParts($ext, $absFile);
    }
}
