<?php

require_once __DIR__ . "/vendor/autoload.php";
include_once "Fury/fury.php";
$app = fury_init("SHServ");

function console() {
	global $argv;

	switch($argv[1]) {
		case "get.config":
			echo json_encode(FCONF);
		break;

		case "migrate":
			$tb = app()->thin_builder;
			$migrationsDir = __DIR__ . "/database/migrations";

			$tb->query("
				CREATE TABLE IF NOT EXISTS shserv_migrations (
					file_name VARCHAR(255) PRIMARY KEY,
					applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
				) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
			");

			$appliedRows = $tb->select("shserv_migrations", ["file_name"]);
			$applied = array_column($appliedRows, "file_name");
			$files = glob($migrationsDir . "/*.php");
			sort($files);

			foreach($files as $file) {
				$baseName = basename($file);
				if(in_array($baseName, $applied)) {
					echo "[SKIP] {$baseName}\n";
					continue;
				}
				$migration = include $file;
				if(is_callable($migration)) {
					$result = $migration($tb);
					if($result) {
						$tb->insert("shserv_migrations", ["file_name" => $baseName]);
						echo "[OK]   {$baseName}\n";
					} else {
						echo "[FAIL] {$baseName}\n";
					}
				} else {
					echo "[SKIP] {$baseName} (not callable)\n";
				}
			}
			echo "\nDone.\n";
		break;

		default: echo "\nNo command";
	}

	echo "\n";
}

console();