<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

// Optional: enforce auth same as your other endpoints
// session_start(); if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['error'=>'Unauthorized']); exit; }

$apiKey = getenv('GEMINI_API_KEY');
if (!$apiKey) { http_response_code(500); echo json_encode(['error'=>'Missing GEMINI_API_KEY']); exit; }

$payload = [
  'config' => [
    'uses' => 1,
    'expireTime' => gmdate('c', time() + 30 * 60),
    'newSessionExpireTime' => gmdate('c', time() + 60),
    'httpOptions' => ['apiVersion' => 'v1alpha'],
  ],
];

$url = "https://generativelanguage.googleapis.com/v1alpha/auth_tokens?key=" . urlencode($apiKey);

$ch = curl_init($url);
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
  CURLOPT_POSTFIELDS => json_encode($payload),
]);
$res = curl_exec($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode((string)$res, true);
if ($code < 200 || $code >= 300 || empty($data['name'])) {
  http_response_code(502);
  echo json_encode(['error' => 'Token mint failed', 'status' => $code, 'details' => $data ?: $res]);
  exit;
}

echo json_encode(['token' => $data['name']]);
