<?php

declare(strict_types=1);

/**
 * M17 tenant foundations: add user_id to gsc_properties for easier isolation/indexing.
 *
 * Note: isolation is already enforced via google_account_id -> google_accounts.user_id,
 * but this column makes future SaaS/ACL queries simpler and faster.
 *
 * @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');
    }

    $props = '`' . $prefix . 'gsc_properties`';
    $accounts = '`' . $prefix . 'google_accounts`';

    try { $pdo->exec("ALTER TABLE {$props} ADD COLUMN `user_id` int unsigned NOT NULL DEFAULT 1 AFTER `id`"); } catch (\Throwable) {}

    // Backfill from account owner.
    try {
        $pdo->exec(
            "UPDATE {$props} p
             JOIN {$accounts} a ON a.id = p.google_account_id
             SET p.user_id = a.user_id
             WHERE p.user_id IS NULL OR p.user_id = 0 OR p.user_id = 1"
        );
    } catch (\Throwable) {}

    try { $pdo->exec("ALTER TABLE {$props} ADD KEY `idx_user_enabled` (`user_id`, `is_enabled`)"); } catch (\Throwable) {}
    try { $pdo->exec("ALTER TABLE {$props} ADD KEY `idx_user_site` (`user_id`, `site_url`(255))"); } catch (\Throwable) {}
};

