<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();
$ftUid = dbnToolsFreeTierCheck('extract');
$ftRemaining = dbnToolsFreeTierDeduct($ftUid, 'extract');
if ($ftRemaining >= 0) { header('X-Credits-Remaining: ' . $ftRemaining); }

try {
    if (empty($_FILES['file']) || !is_array($_FILES['file'])) {
        dbnToolsError('No file was uploaded.', 422, 'missing_file');
    }

    $result = dbnToolsExtractUploadedFile($_FILES['file']);
    dbnToolsRespond($result);
} catch (DbnToolsHttpException $e) {
    dbnToolsError($e->getMessage(), $e->status, $e->errorCode, $e->extra);
} catch (Throwable $e) {
    error_log('DBN extract error: ' . $e->getMessage());
    dbnToolsError('Text extraction failed.', 500, 'extract_error');
}
