<?php

declare(strict_types=1);

return static function (string $tableSuffix): callable {
    return static function (PDO $pdo) use ($tableSuffix): void {
        $systemRoot = dirname(__DIR__, 2);
        require_once $systemRoot . '/support/Support.php';
        require_once $systemRoot . '/media/PublicMediaRenditionService.php';

        $driver = (string) $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
        $tableExists = static function (string $table) use ($pdo, $driver): bool {
            if ($driver === 'sqlite') {
                $statement = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name=" . $pdo->quote($table));
                return $statement !== false && $statement->fetchColumn() !== false;
            }

            $statement = $pdo->prepare('SHOW TABLES LIKE :table');
            $statement->execute([':table' => $table]);
            return $statement->fetchColumn() !== false;
        };

        if (!$tableExists('files')) {
            return;
        }

        $summary = myronPublicMediaRenditionService()->backfillFromDatabase($pdo);
        error_log('[static-media-backfill] APO-438 summary: ' . json_encode($summary, JSON_UNESCAPED_SLASHES));
    };
};
