<?php

it('returns pagination metadata and strict status handling for collected-invoice queue list', function (): void {
    $content = file_get_contents(app_path('routes/orderInvoicesRoute.php'));

    expect($content)->not->toBeFalse();
    $content = (string)$content;

    $start = strpos($content, "\$this->get('/collected-invoices/economic/queue'");
    $end = strpos($content, "\$this->get('/collected-invoices/economic/queue/status'");
    expect($start)->not->toBeFalse();
    expect($end)->not->toBeFalse();
    expect($end)->toBeGreaterThan($start);

    $endpointBlock = substr($content, (int)$start, (int)$end - (int)$start);
    expect($endpointBlock)->toContain('$statuses = $this->parseCollectedInvoiceQueueStatuses();');
    expect($endpointBlock)->toContain("['limit' => \$limit, 'offset' => \$offset] = \$this->parseCollectedInvoiceQueuePagination();");
    expect($endpointBlock)->toContain('$jobs = $queue->listJobsForCreatedBy(');
    expect($endpointBlock)->toContain('economic_transfer_queue::TYPE_COLLECTED_INVOICE_EXPORT');
    expect($endpointBlock)->toContain('$total_jobs = $this->countCollectedInvoiceQueueJobs($queue, $statuses, (int)$user->id);');
    expect($endpointBlock)->toContain("'items' => \$this->withCollectedInvoiceQueueDetailsSummaryList(\$jobs)");
    expect($endpointBlock)->toContain("'total' => \$total_jobs");
    expect($endpointBlock)->toContain("'limit' => \$limit");
    expect($endpointBlock)->toContain("'offset' => \$offset");
    expect($endpointBlock)->toContain("'has_more' => \$has_more");

    expect($content)->toContain('private function parseCollectedInvoiceQueueStatuses(): array');
    expect($content)->toContain('status must contain only: ');
    expect($content)->toContain('private function parseCollectedInvoiceQueuePagination(): array');
    expect($content)->toContain('limit must be between 1 and 500');
    expect($content)->toContain('offset must be at least 0');
    expect($content)->toContain('private function countCollectedInvoiceQueueJobs(economic_transfer_queue $queue, array $statuses, int $created_by): int');
    expect($content)->toContain("method_exists(\$queue, 'countJobsForCreatedBy')");
    expect($content)->toContain("SELECT COUNT(*) AS total FROM economic_transfer_queue_jobs WHERE ");
    expect($content)->toContain("'created_by = ' . \$created_by");
});

it('enforces retry constraints for collected-invoice queue jobs before retry execution', function (): void {
    $content = file_get_contents(app_path('routes/orderInvoicesRoute.php'));

    expect($content)->not->toBeFalse();
    $content = (string)$content;

    $start = strpos($content, "\$this->post('/collected-invoices/economic/queue/retry'");
    $end = strpos($content, "\$this->post('/collected-invoices/move-multiple/registration-numbers'");
    expect($start)->not->toBeFalse();
    expect($end)->not->toBeFalse();
    expect($end)->toBeGreaterThan($start);

    $endpointBlock = substr($content, (int)$start, (int)$end - (int)$start);
    expect($endpointBlock)->toContain('$job_id = $this->requireCollectedInvoiceQueueJobId();');
    expect($endpointBlock)->toContain('$job = $this->requireCollectedInvoiceQueueJobById($job_id, (int)$user->id, true);');
    expect($endpointBlock)->toContain("Collected invoice queue job reached max retry attempts', 409");
    expect($endpointBlock)->toContain('Failed to retry collected invoice queue job: ');
    expect($endpointBlock)->toContain("'job' => \$this->withCollectedInvoiceQueueDetailsSummary(\$retried)");

    expect($content)->toContain("\$response->success(\$this->withCollectedInvoiceQueueDetailsSummary(\$job));");

    expect($content)->toContain('private function requireCollectedInvoiceQueueJobId(): int');
    expect($content)->toContain('private function requireCollectedInvoiceQueueJobById(int $job_id, int $created_by, bool $mustBeFailed = false): array');
    expect($content)->toContain("Collected invoice queue job can only be retried when status is FAILED', 409");
    expect($content)->toContain('private function withCollectedInvoiceQueueDetailsSummary(array $job): array');
    expect($content)->toContain('private function withCollectedInvoiceQueueDetailsSummaryList(array $jobs): array');
    expect($content)->toContain('private function resolveCollectedInvoiceQueueCustomerSummary(array $customer, int $collected_invoice_id): array');
    expect($content)->toContain('FROM collected_order_invoices coi');
    expect($content)->toContain('LEFT JOIN users u ON u.customer_number = coi.customer_number');
    expect($content)->toContain('private function resolveCollectedInvoiceQueueRetryErrorStatus(string $message): int');
    expect($content)->toContain('only failed jobs can be retried');
    expect($content)->toContain('max retry attempts');
});

it('exposes collected-invoice queue monitor and per-user terminal clear routes', function (): void {
    $content = file_get_contents(app_path('routes/orderInvoicesRoute.php'));

    expect($content)->not->toBeFalse();
    $content = (string)$content;

    $monitorStart = strpos($content, "\$this->get('/collected-invoices/economic/queue/monitor'");
    $dismissStart = strpos($content, "\$this->post('/collected-invoices/economic/queue/dismiss'");
    $dismissTerminalStart = strpos($content, "\$this->post('/collected-invoices/economic/queue/dismiss-terminal'");

    expect($monitorStart)->not->toBeFalse();
    expect($dismissStart)->not->toBeFalse();
    expect($dismissTerminalStart)->not->toBeFalse();

    expect($content)->toContain('$limit = $this->parseCollectedInvoiceQueueMonitorLimit();');
    expect($content)->toContain('$this->buildCollectedInvoiceQueueMonitorPayload(');
    expect($content)->toContain('private function parseCollectedInvoiceQueueMonitorLimit(): int');
    expect($content)->toContain('limit must be between 1 and 100');
    expect($content)->toContain('private function buildCollectedInvoiceQueueMonitorPayload(economic_transfer_queue $queue, int $user_id, int $limit): array');
    expect($content)->toContain('$queue->listMonitorJobsForUser(');
    expect($content)->toContain("'queued' => 0");
    expect($content)->toContain("'in_progress' => 0");
    expect($content)->toContain("'progress_percent' => \$counts['total'] > 0");

    expect($content)->toContain('$queue->dismissTerminalJobForUser($job_id, (int)$user->id);');
    expect($content)->toContain('Only completed or failed collected invoice queue jobs can be cleared');
    expect($content)->toContain('$queue->dismissTerminalJobsForUser(');
    expect($content)->toContain("'dismissed_count' => \$dismissed_count");
});

it('runs collected-invoice queue batches through an explicit manual endpoint', function (): void {
    $content = file_get_contents(app_path('routes/orderInvoicesRoute.php'));

    expect($content)->not->toBeFalse();
    $content = (string)$content;

    $start = strpos($content, "\$this->post('/collected-invoices/economic/queue/run'");
    $end = strpos($content, "\$this->post('/collected-invoices/move-multiple/registration-numbers'");
    expect($start)->not->toBeFalse();
    expect($end)->not->toBeFalse();
    expect($end)->toBeGreaterThan($start);

    $endpointBlock = substr($content, (int)$start, (int)$end - (int)$start);
    expect($endpointBlock)->toContain("\$this->ensureEconomicTransferQueueIsAvailable();");
    expect($endpointBlock)->toContain("\$limit = 10;");
    expect($endpointBlock)->toContain("limit must be a positive integer");
    expect($endpointBlock)->toContain("\$limit = max(1, min(10, \$limit));");
    expect($endpointBlock)->toContain("\$batch = \$this->runCollectedInvoiceQueueBatch(\$queue, \$limit);");
    expect($endpointBlock)->toContain("\$result = (array)(\$batch['result'] ?? []);");
    expect($endpointBlock)->toContain("economic_transfer_queue::TYPE_COLLECTED_INVOICE_EXPORT");
    expect($endpointBlock)->toContain("'message' => (bool)(\$batch['fallback'] ?? false)");
    expect($endpointBlock)->toContain("'processed' => (int)(\$result['processed'] ?? 0)");
    expect($endpointBlock)->toContain("'completed' => (int)(\$result['completed'] ?? 0)");
    expect($endpointBlock)->toContain("'failed' => (int)(\$result['failed'] ?? 0)");
    expect($endpointBlock)->toContain("'jobs' => array_values(array_map('intval', (array)(\$result['jobs'] ?? [])))");
    expect($endpointBlock)->toContain("'limit' => \$limit");
    expect($endpointBlock)->toContain("'transfer_type' => economic_transfer_queue::TYPE_COLLECTED_INVOICE_EXPORT");
    expect($endpointBlock)->toContain("'fallback' => (bool)(\$batch['fallback'] ?? false)");

    expect($content)->toContain('private function runCollectedInvoiceQueueBatch(economic_transfer_queue $queue, int $limit): array');
    expect($content)->toContain("method_exists(\$queue, 'processPendingByTransferType')");
    expect($content)->toContain("\$queue->processPendingByTransferType(");
    expect($content)->toContain("\$queue->processPending(\$limit)");
});
