<?php

declare(strict_types=1);

namespace SiteFort\Core\Database;

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

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

final class MigrationRegistry {

	public static function all(): array {
		$migrations = [
			new AuditLogSchemaV1(),
			new ConsoleGateMigration(),
			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;
	}
}
