<?php

declare(strict_types=1);

namespace SecurWP\Core\Database;

use SecurWP\Modules\AuditLog\Migrations\AuditLogSchemaV1;
use SecurWP\Modules\Firewall\Migrations\FirewallEventSchemaV1;
use SecurWP\Modules\Scanner\Migrations\FileIndexSchemaV1;
use SecurWP\Modules\Scanner\Migrations\FileStateSchemaV1;
use SecurWP\Modules\Scanner\Migrations\IssueStoreSchemaV1;
use SecurWP\Modules\Scanner\Migrations\QuarantineSchemaV1;
use SecurWP\Modules\Scanner\Migrations\ScanQueueSchemaV1;
use SecurWP\Modules\Hardening\Migrations\LoginAttemptSchemaV1;
use SecurWP\Modules\TwoFactor\Migrations\TwoFactorSchemaV6;

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

final class MigrationRegistry {

	public static function all(): array {
			$migrations = [
				new AuditLogSchemaV1(),
				new FirewallEventSchemaV1(),
				new LoginAttemptSchemaV1(),
				new FileIndexSchemaV1(),
				new FileStateSchemaV1(),
			new IssueStoreSchemaV1(),
			new QuarantineSchemaV1(),
			new ScanQueueSchemaV1(),
			new TwoFactorSchemaV6(),
		];

		usort(
			$migrations,
			static function ( Migration $left, Migration $right ): int {
				$module_compare = strcmp( $left->module_key(), $right->module_key() );
				if ( $module_compare !== 0 ) {
					return $module_compare;
				}

				return $left->target_version() <=> $right->target_version();
			}
		);

		return $migrations;
	}

	public static function target_schema_map(): array {
		$map = [];

		foreach ( self::all() as $migration ) {
			$module = $migration->module_key();
			$version = $migration->target_version();
			$map[ $module ] = max( (int) ( $map[ $module ] ?? 0 ), $version );
		}

		ksort( $map );

		return $map;
	}
}
