<?php

namespace Planaday\Platform\WordpressConfig\Migrations;

use Planaday\Platform\WordpressConfig\Migrations\Version1\MigrateTo1_0_0;
use Planaday\Platform\WordpressConfig\Migrations\Version1\MigrateTo1_1_0;
use Planaday\Platform\WordpressConfig\Migrations\Version1\MigrateTo1_1_2;
use Planaday\Platform\WordpressConfig\Migrations\Version1\MigrateTo1_2_4;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class MigrationHandler {
	use Logging;
	public function __construct(
		protected Container $container
	) {}

	/**
	 * @param string[] $version
	 *
	 * @return void
	 */
	public function migrate(array $version):void {
		try {
			if (!$this->isCurrentVersionValid($version, [1,0,0])) $this->container->getInstance(MigrateTo1_0_0::class)->migrate();
			if (!$this->isCurrentVersionValid($version, [1,1,0]))$this->container->getInstance(MigrateTo1_1_0::class)->migrate();
			if (!$this->isCurrentVersionValid($version, [1,1,2]))$this->container->getInstance(MigrateTo1_1_2::class)->migrate();
			if (!$this->isCurrentVersionValid($version, [1,2,4]))$this->container->getInstance(MigrateTo1_2_4::class)->migrate();
		} catch ( InjectionImpossibleException $e ) {
			$this->logError("Could not instantiate migration class: {$e->getMessage()}");
		}
	}

	protected function isCurrentVersionValid(array $version, array $targetVersion): bool {
		if ((int)$version[0] !== (int)$targetVersion[0]) return (int)$version[0] > (int)$targetVersion[0];
		if ((int)$version[1] !== (int)$targetVersion[1]) return (int)$version[1] > (int)$targetVersion[1];
		if ((int)$version[2] !== (int)$targetVersion[2]) return (int)$version[2] > (int)$targetVersion[2];
		return true;
	}
}