<?php

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

use App\Request;
use App\Response;
use App\Auth;
use App\SessionManager;
use App\GitHandler;
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 {
    $gitHandler = new GitHandler(Config::get('GIT_STORAGE_PATH', '/tmp/botajs_git'));
    $keys = $gitHandler->generateSSHKey();

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

    // Store in session (backward compatibility)
    $session->set('git_private_key_' . $userId, $keys['private']);
    $session->set('git_public_key_' . $userId, $keys['public']);

    // Store in database (primary storage)
    $db = Database::getInstance();
    $db->storeSSHKey($userId, $keys['public'], $keys['private']);

    Response::success('Deploy key generated successfully', [
        'public_key' => $keys['public'],
        'note' => 'Copy this key and add it as a Deploy Key in your GitHub repository settings'
    ]);
} catch (\Exception $e) {
    Response::error($e->getMessage(), 500);
}