<?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);

$errors = $request->validate([
    'botId' => 'required',
    'git_repo_url' => 'required',
    'api_key' => 'required',
]);

if (!empty($errors)) {
    Response::error('Validation failed', 400, $errors);
}

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

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

    if ($keyData) {
        $sshPrivateKey = $keyData['private_key'];
    } else {
        // Fallback to session (backward compatibility)
        $sshPrivateKey = $session->get('git_private_key_' . $userId);
    }

    if (!$sshPrivateKey) {
        Response::error('SSH key not configured. Generate one first.', 400);
    }

    $gitHandler = new GitHandler(Config::get('GIT_STORAGE_PATH', '/tmp/botajs_git'));

    $result = $gitHandler->exportBot(
        $request->get('botId'),
        $request->get('git_repo_url'),
        $request->get('git_branch'),
        $request->get('commit_message'),
        $sshPrivateKey,
        $request->get('user_email') ?? 'bot@botajs.top',
        $request->get('api_key')
    );

    Response::success($result['message'], $result);
} catch (\Exception $e) {
    Response::error($e->getMessage(), 500);
}