<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$cfg = require __DIR__ . '/../config.php';
require_once __DIR__ . '/SocialService.php';

function respond(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

$service = new SocialService($cfg);
$raw = file_get_contents('php://input') ?: '';
$body = $raw === '' ? [] : json_decode($raw, true);
if (!is_array($body)) {
  respond(400, ['ok' => false, 'error' => 'Invalid JSON']);
}

$ref = trim((string)($body['ref'] ?? ''));
$provider = strtolower(trim((string)($body['provider'] ?? '')));
$draftId = trim((string)($body['draft_id'] ?? ''));
$payload = $body['payload'] ?? null;

if ($ref === '' || !preg_match('/^t_[a-f0-9]{16}$/', $ref)) {
  respond(400, ['ok' => false, 'error' => 'Invalid tenant_ref']);
}

if (!$service->validProvider($provider)) {
  respond(400, ['ok' => false, 'error' => 'Unknown provider']);
}

if ($draftId === '') {
  respond(400, ['ok' => false, 'error' => 'draft_id required']);
}

if (!is_array($payload)) {
  respond(400, ['ok' => false, 'error' => 'payload must be an object']);
}

$job = [
  'provider' => $provider,
  'draft_id' => $draftId,
  'payload' => $payload,
];

if (!$service->queueJob($ref, $job)) {
  respond(500, ['ok' => false, 'error' => 'Failed to enqueue job']);
}

respond(201, ['ok' => true, 'message' => 'Job queued']);
