<?php
// Usage: php create-cert.php --save-dir=/path/to/dir [--bits=4096] [--passphrase=secret] [--overwrite]

chdir(__DIR__ . '/../');
require __DIR__ . '/../../../autoload.php';

$pkgConfigFile = __DIR__ . '/../config/create-cert.php';
$config = [];
if (is_file($pkgConfigFile)) {
    $config = require $pkgConfigFile;
}

$opts = getopt('', ['save-dir::', 'bits::', 'passphrase::', 'overwrite', 'help']);
if (isset($opts['help'])) {
    echo "Usage: php create-cert.php --save-dir=/path [--bits=2048|4096] [--passphrase=pass] [--overwrite]\n";
    exit(0);
}

$saveDir = $opts['save-dir'] ?? ($config['saveDir'] ?? null);
$bits = isset($opts['bits']) ? (int)$opts['bits'] : ($config['bits'] ?? 2048);
$passphrase = $opts['passphrase'] ?? ($config['passphrase'] ?? null);
$overwrite = isset($opts['overwrite']) ? true : ($config['overwrite'] ?? false);

try {
    $result = \PortalPeople\netsuite\components\NetSuiteComponent::generateOAuthCertificate($saveDir, $bits, $passphrase, $overwrite);
} catch (\Exception $e) {
    fwrite(STDERR, "Error generating certificate: " . $e->getMessage() . "\n");
    exit(1);
}

if (!empty($result['private_path']) || !empty($result['public_path'])) {
    echo "Saved files:\n";
    echo " - private: " . ($result['private_path'] ?? '(in-memory)') . "\n";
    echo " - public:  " . ($result['public_path'] ?? '(in-memory)') . "\n";
}

if (!empty($result['certificate_path'])) {
    echo " - certificate: " . $result['certificate_path'] . "\n";
}

echo "--- X.509 Certificate (PEM) - paste this into NetSuite Integration ---\n";
echo $result['certificate_pem'] . "\n";
echo "--- End Certificate ---\n";

echo "--- Public Key (optional) ---\n";
echo $result['public_pem'] . "\n";
echo "--- End Public Key ---\n";

echo "Keep the private key secure (do not commit).\n";
