<?php
/**
 * Open a QA run and print its run_id. Called by the console runner (which has no
 * DB driver) before it starts crawling.
 *
 *   php api/cli/qa-start.php --trigger=manual   # or --trigger=scheduled
 */

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

$opts = getopt('', ['trigger::']);
$trigger = in_array(($opts['trigger'] ?? ''), ['manual', 'scheduled'], true) ? $opts['trigger'] : 'manual';

$pdo = new PDO(
    sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', DB_HOST, DB_NAME),
    DB_USER,
    DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$stmt = $pdo->prepare("INSERT INTO cja_qa_runs (status, `trigger`, started_at) VALUES ('running', ?, NOW())");
$stmt->execute([$trigger]);

echo json_encode(['run_id' => (int) $pdo->lastInsertId()]);
