<?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\QuarantineRepository;

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

final class QuarantineSchemaV1 implements Migration {

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

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

	public function is_applied(): bool {
		return QuarantineRepository::is_schema_current();
	}

	public function apply(): bool {
		QuarantineRepository::ensure_table();
		$this->repair_schema();
		return QuarantineRepository::is_schema_current();
	}

	private function repair_schema(): void {
		$table = QuarantineRepository::get_table_name();
		if ( ! SchemaInspector::table_exists( $table ) ) {
			return;
		}

		$status_column = SchemaInspector::get_column( $table, 'status' );
		if ( ! is_array( $status_column ) ) {
			return;
		}

		$type = strtolower( (string) ( $status_column['Type'] ?? '' ) );
		$null = strtoupper( (string) ( $status_column['Null'] ?? '' ) );
		$default = SchemaInspector::normalize_default_value( $status_column['Default'] ?? '' );

		if ( $type === 'varchar(32)' && $null === 'NO' && $default === 'staged' ) {
			return;
		}

		global $wpdb;
		if ( $table === '' || strlen( $table ) > 64 || ! preg_match( '/^[A-Za-z0-9_]+$/', $table ) ) {
			throw new \InvalidArgumentException( 'Invalid table identifier.' );
		}

		$table_identifier = '`' . str_replace( '`', '``', $table ) . '`';
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query(
			"ALTER TABLE {$table_identifier} MODIFY status varchar(32) NOT NULL DEFAULT 'staged'"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery.SchemaChange

		SchemaInspector::flush_cache( $table );
	}
}
