
<?php
// One-time setup helper. Delete this file after creating the ER token.
require_once __DIR__ . '/../../config/database.php';
$db = (new Database())->getConnection();
$db->exec("CREATE TABLE IF NOT EXISTS api_clients (
    id INT AUTO_INCREMENT PRIMARY KEY,
    client_name VARCHAR(120) NOT NULL,
    token_hash VARCHAR(255) NOT NULL,
    permissions JSON NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    last_used_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_api_clients_name (client_name),
    INDEX idx_api_clients_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$name = $_GET['name'] ?? 'typescript_er';
$token = bin2hex(random_bytes(32));
$hash = password_hash($token, PASSWORD_DEFAULT);
$stmt = $db->prepare('INSERT INTO api_clients (client_name, token_hash, permissions) VALUES (:name,:hash,:perms) ON DUPLICATE KEY UPDATE token_hash=VALUES(token_hash), permissions=VALUES(permissions), is_active=1');
$stmt->execute([':name'=>$name, ':hash'=>$hash, ':perms'=>json_encode(['tickets:list','tickets:create','tickets:update','tickets:delete'])]);
header('Content-Type: text/plain');
echo "Client: {$name}\nToken: {$token}\n\nSave this token in ER/TypeScript environment variables. Delete create_client_token.php after setup.\n";
