<?php
require_once '/opt/collabit-hub/timefold_webhook_hub_lib.php';

$send = static function (int $code, array $payload): void {
    http_response_code($code);
    header('Content-Type: application/json');
    echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . "\n";
    exit;
};

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'GET' && isset($_GET['health'])) {
    $cust = trim((string)($_GET['cust'] ?? ''));
    $route = $cust !== '' ? tfhub_resolve_route($cust) : null;
    $send(200, [
        'ok' => true,
        'mode' => 'hub_relay',
        'queue_dir' => tfhub_base_dir(),
        'queue_writable' => is_writable(rtrim(tfhub_base_dir(), '/') . '/pending'),
        'hmac_configured' => tfhub_secret() !== '',
        'counts' => tfhub_counts(),
        'route' => $route,
    ]);
}

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

$rawBody = (string)file_get_contents('php://input');
if ($rawBody === '') {
    tfhub_log('REJECT_EMPTY_BODY');
    $send(400, ['ok' => false, 'error' => 'empty_body']);
}

$payload = json_decode($rawBody, true);
if (!is_array($payload)) {
    tfhub_log('REJECT_INVALID_JSON', ['body_sha256' => hash('sha256', $rawBody)]);
    $send(400, ['ok' => false, 'error' => 'invalid_json']);
}

$headers = tfhub_headers();
$secret = tfhub_secret();
if ($secret === '') {
    tfhub_log('REJECT_NO_SECRET', ['body_sha256' => hash('sha256', $rawBody)]);
    $send(500, ['ok' => false, 'error' => 'missing_hmac_secret']);
}

$path = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH) ?: '/timefold_webhook.php');
$verify = tfhub_verify_hmac($rawBody, $headers, $path, (string)($_SERVER['REQUEST_METHOD'] ?? 'POST'), $secret);
if (empty($verify['ok'])) {
    tfhub_log('REJECT_HMAC', ['error' => $verify['error'] ?? 'unknown', 'body_sha256' => hash('sha256', $rawBody)]);
    $send(401, ['ok' => false, 'error' => 'invalid_hmac']);
}

$context = tfhub_extract_context($payload);
$result = tfhub_enqueue($payload, $rawBody, $headers, $context);
if (empty($result['ok'])) {
    tfhub_log('REJECT_QUEUE', ['error' => $result['error'] ?? 'unknown', 'context' => $context]);
    $send(400, ['ok' => false, 'error' => $result['error'] ?? 'queue_error', 'context' => $context]);
}

$kick = tfhub_kick_worker();
tfhub_log(!empty($result['duplicate']) ? 'DUPLICATE' : 'QUEUED', [
    'cust' => $context['cust'] ?? '',
    'request_id' => $context['request_id'] ?? 0,
    'run_id' => $context['run_id'] ?? '',
    'path' => $result['path'] ?? '',
    'target_url' => $result['target_url'] ?? '',
    'worker_started' => !empty($kick['started']),
    'worker_reason' => $kick['reason'] ?? '',
]);

$send(200, [
    'ok' => true,
    'queued' => empty($result['duplicate']),
    'duplicate' => !empty($result['duplicate']),
    'worker_kicked' => !empty($kick['started']),
    'cust' => $context['cust'] ?? '',
    'request_id' => $context['request_id'] ?? 0,
    'run_id' => $context['run_id'] ?? '',
]);
