<?php
// scripts/seed_jupyterhub_client.php
// Inserts or updates the JupyterHub OAuth client using environment values.

require_once __DIR__ . '/../config.php';

$clientId = getenv('DSP_OAUTH_CLIENT_ID');
$clientSecret = getenv('DSP_OAUTH_CLIENT_SECRET');
$redirectUris = getenv('DSP_OAUTH_REDIRECT_URIS') ?: (getenv('JUPYTERHUB_OAUTH_CALLBACK') ?: '');
$allowedScopes = getenv('DSP_OAUTH_ALLOWED_SCOPES') ?: 'profile';

if (!$clientId || !$clientSecret || !$redirectUris) {
    fwrite(STDERR, "Missing DSP_OAUTH_CLIENT_ID, DSP_OAUTH_CLIENT_SECRET, or redirect URIs.\n");
    exit(1);
}

$clientName = getenv('DSP_OAUTH_CLIENT_NAME') ?: 'DSP JupyterHub';
$hashedSecret = password_hash($clientSecret, PASSWORD_DEFAULT);

$query = <<<SQL
INSERT INTO dsp_oauth_clients (
    client_id,
    client_name,
    client_secret_hash,
    redirect_uris,
    allowed_scopes,
    is_confidential,
    is_revoked,
    updated_at
) VALUES (
    :client_id,
    :client_name,
    :client_secret_hash,
    :redirect_uris,
    :allowed_scopes,
    1,
    0,
    NOW()
)
ON DUPLICATE KEY UPDATE
    client_name = VALUES(client_name),
    client_secret_hash = VALUES(client_secret_hash),
    redirect_uris = VALUES(redirect_uris),
    allowed_scopes = VALUES(allowed_scopes),
    is_confidential = 1,
    is_revoked = 0,
    updated_at = NOW();
SQL;

$stmt = $pdo->prepare($query);
$stmt->execute([
    ':client_id' => $clientId,
    ':client_name' => $clientName,
    ':client_secret_hash' => $hashedSecret,
    ':redirect_uris' => $redirectUris,
    ':allowed_scopes' => $allowedScopes,
]);

echo "OAuth client '{$clientId}' has been seeded.\n";
