<?php
/**
 * Promote Validation Strategy to Production — LEGACY ALIAS.
 *
 * POST /api/migrate/promote-validation.php
 * Body: { "strategy_id": "uuid" }
 *
 * This endpoint used to contain its own independent graduation
 * implementation (flip is_validation on the strategy + its trades). That
 * logic has been consolidated into ValidationService::graduate()
 * (src/ValidationService.php) — the single graduation path in the app,
 * now also enforcing the Validation Workflow's 50-trade minimum
 * server-side (this endpoint previously had no such check at all) and
 * flipping the user's workflow_state to 'main' + recording provenance,
 * neither of which existed here before.
 *
 * This file is kept only so any existing bookmark/integration hitting
 * this exact URL keeps working, with the SAME response shape it always
 * returned (success/error/strategy_id/strategy_name/versions_migrated/
 * trades_migrated/promoted_at) — new callers should use
 * POST /api/validation/graduate directly.
 */

define('NO_HTML_OUTPUT', true);

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../src/ScopedDb.php';
require_once __DIR__ . '/../../src/Auth.php';
require_once __DIR__ . '/../../src/ValidationService.php';

header('Content-Type: application/json');

if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

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

try {
    $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed.']);
    exit;
}

$auth = new Auth($pdo);
$userId = $auth->requireAuth();

if (!$userId) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Authentication required.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$strategyId = $input['strategy_id'] ?? $_POST['strategy_id'] ?? null;

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

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

if (!$result['success']) {
    http_response_code(($result['error'] ?? '') === 'Strategy not found or access denied.' ? 404 : 400);
    echo json_encode($result);
    exit;
}

// Legacy response shape — same field names this endpoint always returned.
http_response_code(200);
echo json_encode([
    'success'           => true,
    'message'           => 'Strategy promoted to production',
    'strategy_id'       => $result['strategy_id'],
    'strategy_name'     => $result['strategy_name'],
    'versions_migrated' => $result['versions_migrated'],
    'trades_migrated'   => $result['trades_migrated'],
    'promoted_at'       => date('Y-m-d H:i:s'),
]);
