<?php
/**
 * GET /api/dashboard/ingest-status.php?ids=1,2,3
 *
 * Returns per-doc status for polling during URL ingest (background) or to
 * surface error messages after a failed sync upload.
 *
 * Response:
 *   { ok, statuses: [ {id, status, chunk_count, error_message}, ... ] }
 */

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/includes/bootstrap.php';

dbnToolsRequireMethod('GET');
dbnToolsRequireAuth();

try {
    $tenant = dbnToolsEnsureDashboardTenant();
} catch (DbnToolsHttpException $e) {
    dbnToolsError($e->getMessage(), $e->status, $e->errorCode);
}
$clientId = (int)$tenant['client_id'];

$raw = (string)($_GET['ids'] ?? '');
$ids = array_values(array_filter(
    array_map('intval', explode(',', $raw)),
    fn($v) => $v > 0
));
if (!$ids) {
    dbnToolsRespond(['ok' => true, 'statuses' => []]);
}
$ids = array_slice($ids, 0, 100);

$db = dbnToolsDb();
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "SELECT id, status, chunk_count, error_message
        FROM client_documents
        WHERE client_id = ? AND id IN ({$placeholders})";
$stmt = $db->prepare($sql);
$stmt->execute(array_merge([$clientId], $ids));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

dbnToolsRespond([
    'ok'       => true,
    'statuses' => array_map(fn($r) => [
        'id'            => (int)$r['id'],
        'status'        => (string)$r['status'],
        'chunk_count'   => (int)$r['chunk_count'],
        'error_message' => $r['error_message'] ?? null,
    ], $rows),
]);
