<?php
/**
 * POST /api/validation/graduate — Validation Workflow graduation.
 *
 * $auth/$db/$pdo are set up by index.php's router (same pattern as
 * api/journal/update-account-meta.php). All real logic lives in
 * ValidationService::graduate() (src/ValidationService.php, already
 * required globally by index.php) — this file is a thin HTTP wrapper,
 * per the Validation Workflow spec's "ValidationService is an
 * orchestrator, not a competing calculation/business-logic brain living
 * in the endpoint" principle.
 *
 * Body: { "strategy_id": "uuid", "force": false }
 *
 * "force" (2026-08-12 edge-warning pass) is the ONLY way to graduate a
 * strategy that hasn't demonstrated a profitable edge yet
 * (ValidationService::evaluateEdge()) — enforced inside
 * ValidationService::graduate() itself, not here, so this stays a thin
 * wrapper. Omitting it (or sending false) against an edge-negative
 * strategy returns {success:false, warning:true, metrics:{...}} instead
 * of a graduation — the Tracker's JS uses that shape to show the warning
 * UI and, only on explicit "Continue Anyway," re-POSTs with force:true.
 *
 * This is now the SINGLE graduation path in the app — see
 * public/journal-validation.php (its old inline promote handler now just
 * calls this) and api/migrate/promote-validation.php (now a thin,
 * backward-compatible alias onto the same service call). Both of those
 * previously had their own independent, inconsistent graduation logic —
 * one silently left trades.is_validation=1 after "promoting," which would
 * have made graduated trades invisible to every main-workflow query.
 */
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed. Use POST.']);
    exit;
}

$userId = $auth->requireAuth();

$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) { $input = []; }
$strategyId = $input['strategy_id'] ?? $_POST['strategy_id'] ?? null;
$force = filter_var($input['force'] ?? $_POST['force'] ?? false, FILTER_VALIDATE_BOOLEAN);

if (empty($strategyId)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'strategy_id is required.']);
    exit;
}

$result = ValidationService::graduate($userId, $strategyId, $pdo, $db, $force);

http_response_code($result['success'] ? 200 : 400);
echo json_encode($result);
