<?php
declare(strict_types=1);
/**
 * GET /api/corpus-summary.php
 * Returns: { doc_count: int, last_updated: string|null }
 *
 * Auth: SSO session only. Ensures dashboard tenant is provisioned.
 */
require_once __DIR__ . '/../includes/bootstrap.php';

header('Content-Type: application/json');
header('Cache-Control: no-store');

if (!dbnToolsIsAuthenticated() || !dbnToolsIsFreeTier()) {
    http_response_code(401);
    echo json_encode(['error' => 'auth_required']);
    exit;
}

try {
    $tenant = dbnToolsEnsureDashboardTenant();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['error' => 'tenant_unavailable']);
    exit;
}

try {
    $db = dbnToolsDb();
    $stmt = $db->prepare(
        "SELECT COUNT(*) AS doc_count, MAX(created_at) AS last_updated
           FROM client_documents
          WHERE client_id = ? AND status = 'ready'"
    );
    $stmt->execute([(int)$tenant['client_id']]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'doc_count'    => (int)($row['doc_count'] ?? 0),
        'last_updated' => $row['last_updated'] ?? null,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'db_error']);
}
