<?php

declare(strict_types=1);

namespace SiteFort\Modules\Scanner\Migrations;

use SiteFort\Core\Database\Migration;
use SiteFort\Core\Database\SchemaInspector;
use SiteFort\Modules\Scanner\Repository\ScanQueueRepository;

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

final class ScanQueueSchemaV1 implements Migration {

	public function module_key(): string {
		return 'scanner_queue';
	}

	public function target_version(): int {
		return 1;
	}

	public function is_applied(): bool {
		global $wpdb;

		$scan_queue = $wpdb->prefix . 'sitefort_scan_queue';
		$task_queue = $wpdb->prefix . 'sitefort_task_queue';

		if (
			! SchemaInspector::table_exists( $scan_queue ) ||
			! SchemaInspector::table_exists( $task_queue )
		) {
			return false;
		}

		if ( ! SchemaInspector::has_columns(
			$scan_queue,
			[
				'component_status',
				'token_bucket_tokens',
				'cloud_error_count',
				'malware_signature_version',
				'next_run_at',
				'last_dispatch_at',
				'task_runner_lease_token',
				'task_runner_lease_until',
				'last_ping',
			]
		) ) {
			return false;
		}

		if ( ! SchemaInspector::has_columns( $task_queue, [ 'lease_until', 'max_attempts', 'dedupe_key' ] ) ) {
			return false;
		}

		return SchemaInspector::has_indexes( $task_queue, [ 'idx_scan_type', 'idx_lease', 'idx_dedupe' ] );
	}

	public function apply(): bool {
		ScanQueueRepository::ensure_tables();
		return true;
	}
}
