<?php

declare(strict_types=1);

/**
 * User-scoped tracked Search Console landing page URLs per property.
 *
 * Store the exact `page` string as in GSC / `gsc_daily_page.page` (full URL, up to 2048 chars).
 * UNIQUE uses a 191-char prefix on `page` (utf8mb4 InnoDB index limit), same trade-off as
 * `gsc_daily_page` and `tracked_queries`.
 *
 * Lifecycle: rows are removed when parent `users` or `gsc_properties` is deleted (ON DELETE CASCADE).
 * `ResetService::resetAllData()` deletes this table before `gsc_properties`.
 *
 * @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_pages`';
    $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,
            `page` varchar(2048) NOT NULL,
            `created_at` datetime NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uniq_user_property_page` (`user_id`, `property_id`, `page`(191)),
            KEY `idx_user_property` (`user_id`, `property_id`),
            CONSTRAINT `fk_tracked_pages_user`
                FOREIGN KEY (`user_id`) REFERENCES {$users} (`id`) ON DELETE CASCADE,
            CONSTRAINT `fk_tracked_pages_property`
                FOREIGN KEY (`property_id`) REFERENCES {$props} (`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );
};
