<?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'] ?? '')));
$payload = $body['token_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 ($payload === null) {
  respond(400, ['ok' => false, 'error' => 'token_payload required']);
}

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

try {
  $saved = $service->storeToken($ref, $provider, $payload);
} catch (Throwable $e) {
  respond(500, ['ok' => false, 'error' => 'Encryption failed', 'details' => $e->getMessage()]);
}

if (!$saved) {
  respond(500, ['ok' => false, 'error' => 'Failed to persist token']);
}

respond(200, ['ok' => true, 'provider' => $provider]);
