<?php
/**
 * سودانا AI Engine — /api/engine/keys.php
 * GET: list keys | POST: generate | DELETE: revoke
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/AIEngine.php';

$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $keys = db()->prepare(
        "SELECT id, key_prefix, label, status, calls_today, calls_total, last_used_at, created_at
         FROM ai_api_keys WHERE user_id=? AND status='active' ORDER BY created_at DESC"
    );
    $keys->execute([$u['id']]);
    json_response(['success'=>true,'keys'=>$keys->fetchAll()]);
}

if ($method === 'POST') {
    $b     = json_decode(file_get_contents('php://input'), true) ?? [];
    $label = mb_substr(trim($b['label'] ?? 'Default Key'), 0, 100);
    $raw   = AIEngine::generateKey((int)$u['id'], $label);
    if (!$raw) Kernel::fail('max_keys_reached', 'Maximum 5 API keys per account', 400);
    json_response(['success'=>true,'api_key'=>$raw,'message'=>'Save this key — it will not be shown again.']);
}

if ($method === 'DELETE') {
    $b  = json_decode(file_get_contents('php://input'), true) ?? [];
    $id = (int)($b['key_id'] ?? 0);
    db()->prepare("UPDATE ai_api_keys SET status='revoked' WHERE id=? AND user_id=?")->execute([$id, $u['id']]);
    json_response(['success'=>true]);
}

Kernel::fail('method_not_allowed', '', 405);
