<?php

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

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

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

$session = new SessionManager();
$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';

    // Try database first (primary storage)
    $db = Database::getInstance();
    $keyData = $db->getSSHKey($userId);

    if ($keyData) {
        Response::json(['public_key' => $keyData['public_key']]);
    }

    // Fallback to session (backward compatibility)
    $publicKey = $session->get('git_public_key_' . $userId);

    if (!$publicKey) {
        Response::error('No SSH key generated yet', 404);
    }

    Response::json(['public_key' => $publicKey]);
} catch (\Exception $e) {
    Response::error($e->getMessage(), 500);
}