<?php

declare(strict_types=1);

namespace SiteFort\Modules\Scanner\Queue\Handler;

use SiteFort\Modules\Scanner\Queue\ScanOrchestrator;
use SiteFort\Modules\Scanner\Queue\ScanQueue;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Executes one cloud upload batch.
 */
class UploadBatchHandler {

	/**
	 * @param array<string,mixed> $task
	 * @param string              $scan_id
	 * @return TaskResult
	 */
	public function handle( array $task, string $scan_id ): TaskResult {
		$queue = ScanQueue::get_job( $scan_id );
		if ( ! is_array( $queue ) || ! in_array( (string) ( $queue['status'] ?? '' ), [ 'pending', 'running' ], true ) ) {
			return TaskResult::completed( [ 'status' => 'idle' ] );
		}

		$payload = is_array( $task['payload'] ?? null ) ? $task['payload'] : [];

		try {
			$orchestrator = new ScanOrchestrator( $scan_id );
			$result = $orchestrator->run_upload_batch_task( $payload );
			$follow_ups = [];

			if ( ! empty( $result['job_id'] ) ) {
				if ( ! class_exists( '\SiteFort\Modules\Scanner\Service\ScanLogger' ) ) {
					require_once dirname( dirname( __DIR__ ) ) . '/Service/ScanLogger.php';
				}
				\SiteFort\Modules\Scanner\Service\ScanLogger::log(
					sprintf(
						'Submitted %d file(s) to cloud analysis. Awaiting results...',
						(int) ( $result['uploaded_count'] ?? 0 )
					)
				);
				$follow_ups[] = [
					'task_type'    => 'poll_cloud',
					'payload'      => [
						'poll_count'  => 0,
					],
					'available_at' => time() + 10,
					'priority'     => 60,
					'dedupe_key'   => TaskResult::build_scan_poll_dedupe_key(),
				];
			}

			if ( ! empty( $result['has_more'] ) ) {
				$follow_ups[] = [
					'task_type'    => 'upload_batch',
					'payload'      => $payload,
					'available_at' => time(),
					'priority'     => 70,
				];
			}

			if ( $orchestrator->has_file_worker_work() ) {
				$follow_ups[] = [
					'task_type'    => 'scan_worker',
					'payload'      => [ 'budget_seconds' => 20 ],
					'available_at' => time(),
					'priority'     => 100,
				];
			}

			if ( $orchestrator->is_ready_for_finalize() ) {
				$follow_ups[] = [
					'task_type'    => 'finalize',
					'payload'      => [ 'scan_id' => $scan_id ],
					'available_at' => time(),
					'priority'     => 10,
					'dedupe_key'   => 'finalize',
				];
			}

			return TaskResult::completed(
				[
					'status'        => 'completed',
					'uploaded_count'=> (int) ( $result['uploaded_count'] ?? 0 ),
					'job_id'        => $result['job_id'] ?? null,
				],
				$follow_ups
			);
		} catch ( \Throwable $e ) {
			return TaskResult::failed( sanitize_text_field( $e->getMessage() ) );
		}
	}

}
