<?php

declare(strict_types=1);

return static function (string $tableSuffix): callable {
    return static function (PDO $pdo): void {
        $driver = (string) $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
        $hasColumn = static function (string $table, string $column) use ($pdo, $driver): bool {
            if ($driver === 'sqlite') {
                $statement = $pdo->query('PRAGMA table_info(' . $table . ')');
                foreach (($statement ? $statement->fetchAll(PDO::FETCH_ASSOC) : []) as $row) {
                    if (strtolower((string) ($row['name'] ?? '')) === strtolower($column)) {
                        return true;
                    }
                }
                return false;
            }

            $statement = $pdo->prepare(
                'SELECT COUNT(*)
                 FROM information_schema.columns
                 WHERE table_schema = DATABASE()
                   AND table_name = :table
                   AND column_name = :column'
            );
            $statement->execute([':table' => $table, ':column' => $column]);
            return (int) $statement->fetchColumn() > 0;
        };

        $addColumn = static function (string $table, string $column, string $definition) use ($pdo, $hasColumn): void {
            if (!$hasColumn($table, $column)) {
                $pdo->exec(sprintf('ALTER TABLE %s ADD COLUMN %s %s', $table, $column, $definition));
            }
        };

        $addColumn('pages', 'indexable_override', 'INTEGER DEFAULT NULL');
        $addColumn('site_type_registry', 'indexable', 'INTEGER NOT NULL DEFAULT 1');
        $addColumn('site_settings', 'seo_robots_txt_override', 'TEXT DEFAULT NULL');

        $nonIndexable = ['site-type.mkt', 'site-type.crs'];
        $statement = $pdo->prepare(
            'UPDATE site_type_registry
             SET indexable = :indexable
             WHERE bundle_id = :bundle_id'
        );

        foreach ($nonIndexable as $bundleId) {
            $statement->execute([':indexable' => 0, ':bundle_id' => $bundleId]);
        }
    };
};
