#!/usr/bin/env php
<?php
/**
 * NEMS Linux API Key Management Utility
 * Usage: nems-api-key create "Home Assistant" [--raw | --json]
 */

if (php_sapi_name() !== 'cli') {
    die("This script can only be run from the CLI.\n");
}

$db_path = '/usr/local/share/nems/database/nems_config.db';

// Extract flags and rebuild arguments
$isRaw = in_array('--raw', $argv);
$isJson = in_array('--json', $argv);
$args = array_values(array_filter($argv, fn($val) => !in_array($val, ['--raw', '--json'])));

$action  = $args[1] ?? 'help';
$desc    = $args[2] ?? 'Default API Key';

if ($action === 'create') {
    $rawToken = 'nems_live_' . bin2hex(random_bytes(16));
    $hash     = hash('sha256', $rawToken);
    $uuid     = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));

    try {
        $db = new PDO("sqlite:{$db_path}");
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $db->prepare("
            INSERT INTO api_keys (key_uuid, token_hash, description, scope_read, scope_config, scope_ops, scope_admin, created_by)
            VALUES (:uuid, :hash, :desc, 1, 1, 1, 1, 'cli_admin')
        ");
        $stmt->execute([
            ':uuid' => $uuid,
            ':hash' => $hash,
            ':desc' => $desc
        ]);

        if ($isRaw) {
            echo $rawToken;
        } elseif ($isJson) {
            echo json_encode(['status' => 'SUCCESS', 'uuid' => $uuid, 'token' => $rawToken, 'description' => $desc]);
        } else {
            echo "\n=== NEMS API Key Generated Successfully ===\n";
            echo "Description : {$desc}\n";
            echo "Key UUID    : {$uuid}\n";
            echo "Bearer Token: {$rawToken}\n\n";
            echo "[!] Save this token now! It will not be shown again.\n\n";
        }

    } catch (PDOException $e) {
        if ($isRaw) {
            // output nothing on raw failure so the caller gets an empty string
        } elseif ($isJson) {
            echo json_encode(['status' => 'ERROR', 'message' => $e->getMessage()]);
        } else {
            echo "[-] Error creating API key: " . $e->getMessage() . "\n";
        }
        exit(1);
    }
} elseif ($action === 'list') {
    $db = new PDO("sqlite:{$db_path}");
    $stmt = $db->query("SELECT id, key_uuid, description, scope_read, scope_config, created_at, last_used_at FROM api_keys");
    $keys = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($isJson) {
        echo json_encode(['status' => 'SUCCESS', 'data' => $keys]);
    } else {
        echo "\n=== Active NEMS API Keys ===\n";
        foreach ($keys as $k) {
            echo "ID: {$k['id']} | UUID: {$k['key_uuid']} | Desc: {$k['description']} | Last Used: " . ($k['last_used_at'] ?? 'Never') . "\n";
        }
        echo "\n";
    }
} else {
    echo "Usage:\n";
    echo "  nems-api-key create \"Description\" [--raw | --json]\n";
    echo "  nems-api-key list [--json]\n";
}
