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

$raw = file_get_contents('php://input');
if ($raw === false || $raw === '') {
    json_out(['ok' => false, 'error' => 'empty body'], 400);
}
$data = json_decode($raw, true);
if (!is_array($data)) {
    json_out(['ok' => false, 'error' => 'invalid json'], 400);
}
if ((int) ($data['schema_version'] ?? 0) !== 1) {
    json_out(['ok' => false, 'error' => 'unsupported schema_version'], 400);
}
if (($data['ingest_kind'] ?? 'ticket') !== 'ticket') {
    json_out(['ok' => false, 'error' => 'ingest_kind must be ticket'], 400);
}
try {
    Database::requireTicketsTable();
    TicketRepository::insert($data);
    json_out(['ok' => true, 'ticket_id' => $data['ticket_id'] ?? null]);
} catch (InvalidArgumentException $e) {
    json_out(['ok' => false, 'error' => $e->getMessage()], 400);
} catch (RuntimeException $e) {
    error_log('ticket upload: ' . $e->getMessage());
    json_out(['ok' => false, 'error' => 'tickets_table_missing', 'hint' => $e->getMessage()], 503);
} catch (PDOException $e) {
    $msg = $e->getMessage();
    if ($e->getCode() === '23000' || stripos($msg, 'UNIQUE') !== false) {
        json_out(['ok' => false, 'error' => 'duplicate ticket_id'], 409);
    }
    error_log('ticket upload PDO: ' . $msg);
    $out = ['ok' => false, 'error' => 'store failed'];
    if (cfg('debug')) {
        $out['hint'] = $msg;
    }
    json_out($out, 500);
} catch (Throwable $e) {
    error_log('ticket upload: ' . $e->getMessage());
    $out = ['ok' => false, 'error' => 'store failed'];
    if (cfg('debug')) {
        $out['hint'] = $e->getMessage();
    }
    json_out($out, 500);
}
