<?php
declare(strict_types=1);

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

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

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

$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'] ?? ''));
$key = trim((string)($body['api_key'] ?? ''));

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

try {
  $saved = openai_save_key($cfg, $ref, $key);
} catch (Throwable $e) {
  respond(500, ['ok' => false, 'error' => 'Encryption failure', 'details' => $e->getMessage()]);
}

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

respond(200, ['ok' => true, 'message' => 'Key saved']);
