<?php

require __DIR__ . '/../vendor/autoload.php';

use App\Request;
use App\Response;
use App\Auth;
use App\Config;
use App\Database;

Config::load(__DIR__ . '/../.env');

$request = new Request();

$validKeys = [Config::get('API_KEY', 'your-secret-key')];
$auth = new Auth($request);
$auth->authenticate($validKeys);

try {
    $userId = $request->get('user_id') ?? 'anonymous';

    // Get SSH key from database
    $db = Database::getInstance();
    $keyData = $db->getSSHKey($userId);

    if (!$keyData) {
        Response::json([
            'has_key' => false,
            'message' => 'No SSH key configured for this user',
            'public_key' => null,
            'created_at' => null,
            'updated_at' => null
        ]);
    }

    // Return public key info (never return private key in API response)
    Response::json([
        'has_key' => true,
        'message' => 'SSH key found',
        'public_key' => $keyData['public_key'],
        'created_at' => $keyData['created_at'],
        'updated_at' => $keyData['updated_at'],
        'key_fingerprint' => getKeyFingerprint($keyData['public_key'])
    ]);
} catch (\Exception $e) {
    Response::error($e->getMessage(), 500);
}

/**
 * Generate SSH key fingerprint for display
 */
function getKeyFingerprint($publicKey)
{
    // Extract key type and key data
    $parts = explode(' ', $publicKey, 3);
    if (count($parts) < 2) {
        return null;
    }

    $keyData = base64_decode($parts[1]);
    if (!$keyData) {
        return null;
    }

    // Generate MD5 fingerprint
    $hash = md5($keyData);
    return implode(':', str_split($hash, 2));
}
