<?php

declare(strict_types=1);

/**
 * User-scoped tracked Search Console queries (keywords) per property.
 *
 * Lifecycle: rows are removed automatically when the parent `users` or `gsc_properties`
 * row is deleted (ON DELETE CASCADE). Global “reset all data” wipes this table before
 * properties (see `ResetService::resetAllData()`).
 *
 * @return callable(PDO, string): void
 */
return static function (\PDO $pdo, string $prefix): void {
    if (!preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {
        throw new InvalidArgumentException('Invalid table prefix');
    }

    $t = '`' . $prefix . 'tracked_queries`';
    $users = '`' . $prefix . 'users`';
    $props = '`' . $prefix . 'gsc_properties`';

    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS {$t} (
            `id` bigint unsigned NOT NULL AUTO_INCREMENT,
            `user_id` int unsigned NOT NULL,
            `property_id` bigint unsigned NOT NULL,
            `query` varchar(1024) NOT NULL,
            `created_at` datetime NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uniq_user_property_query` (`user_id`, `property_id`, `query`(191)),
            KEY `idx_user_property` (`user_id`, `property_id`),
            CONSTRAINT `fk_tracked_queries_user`
                FOREIGN KEY (`user_id`) REFERENCES {$users} (`id`) ON DELETE CASCADE,
            CONSTRAINT `fk_tracked_queries_property`
                FOREIGN KEY (`property_id`) REFERENCES {$props} (`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );
};
