<?php

declare(strict_types=1);

/**
 * M17.2 Owner model (non-destructive by design).
 *
 * Adds:
 * - users.is_active: allow safe future deactivation
 * - users.is_owner: marks the installation owner (first admin)
 *
 * Owner is defined as the earliest created user (lowest id). This makes the
 * future "Users" UI safe by allowing guardrails like "owner cannot be disabled
 * or deleted".
 *
 * @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');
    }

    $users = '`' . $prefix . 'users`';

    try { $pdo->exec("ALTER TABLE {$users} ADD COLUMN `is_active` tinyint(1) NOT NULL DEFAULT 1 AFTER `role`"); } catch (\Throwable) {}
    try { $pdo->exec("ALTER TABLE {$users} ADD COLUMN `is_owner` tinyint(1) NOT NULL DEFAULT 0 AFTER `is_active`"); } catch (\Throwable) {}
    try { $pdo->exec("ALTER TABLE {$users} ADD KEY `idx_active` (`is_active`)"); } catch (\Throwable) {}
    try { $pdo->exec("ALTER TABLE {$users} ADD KEY `idx_owner` (`is_owner`)"); } catch (\Throwable) {}

    // Ensure exactly one owner (best-effort): set lowest id as owner.
    try { $pdo->exec("UPDATE {$users} SET is_owner = 0"); } catch (\Throwable) {}
    try {
        $stmt = $pdo->query("SELECT id FROM {$users} ORDER BY id ASC LIMIT 1");
        $ownerId = (int) ($stmt ? $stmt->fetchColumn() : 0);
        if ($ownerId > 0) {
            $upd = $pdo->prepare("UPDATE {$users} SET is_owner = 1, is_active = 1 WHERE id = ? LIMIT 1");
            $upd->execute([$ownerId]);
        }
    } catch (\Throwable) {}
};

