<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';
Auth::check();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_out(['ok' => false, 'error' => 'POST required'], 405);
}

$raw = file_get_contents('php://input') ?: '{}';
$body = json_decode($raw, true);
if (!is_array($body)) {
    $body = $_POST;
}

$action = (string) ($body['action'] ?? '');
$buildId = (int) ($body['build_id'] ?? 0);
if ($buildId <= 0) {
    json_out(['ok' => false, 'error' => 'build_id required'], 400);
}

$user = Auth::user();
$userId = isset($user['id']) ? (int) $user['id'] : null;

try {
    if ($action === 'stop') {
        $ok = BuildRunner::stopBuild($buildId);
        json_out(['ok' => $ok, 'build' => BuildRepository::getById($buildId)]);
    }
    if ($action === 'rerun') {
        $build = BuildRunner::rerunBuild($buildId, null, $userId);
        json_out(['ok' => true, 'build' => $build]);
    }
    if ($action === 'force_rerun') {
        $build = BuildRunner::forceRerun($buildId, $userId);
        json_out(['ok' => true, 'build' => $build]);
    }
    if ($action === 'rerun_as') {
        $override = is_array($body['params'] ?? null) ? $body['params'] : [];
        $build = BuildRunner::rerunBuild($buildId, $override, $userId);
        json_out(['ok' => true, 'build' => $build]);
    }
    if ($action === 'rerun_from_failed') {
        $build = BuildRunner::rerunFromFailed($buildId, $userId, false);
        json_out(['ok' => true, 'build' => $build, 'resume_from' => BuildRunner::detectFailedStep($buildId)]);
    }
    if ($action === 'rerun_with_ssh') {
        $build = BuildRunner::rerunFromFailed($buildId, $userId, true);
        json_out(['ok' => true, 'build' => $build, 'resume_from' => BuildRunner::detectFailedStep($buildId)]);
    }
    json_out(['ok' => false, 'error' => 'unknown_action'], 400);
} catch (Throwable $e) {
    error_log('build_actions: ' . $e->getMessage());
    json_out(['ok' => false, 'error' => $e->getMessage()], 500);
}
