<?php
declare(strict_types=1);

namespace App\Core\Migrations;

use App\Core\Database;
use PDO;

final class MigrationManager
{
    public function __construct(private readonly string $directory)
    {
    }

    /** @return list<array<string,mixed>> */
    public function status(): array
    {
        $applied = $this->appliedVersions();
        $rows = [];
        foreach (glob(rtrim($this->directory, '/\\') . '/*.sql') ?: [] as $file) {
            $version = basename($file, '.sql');
            $rows[] = [
                'version' => $version,
                'file' => basename($file),
                'applied' => isset($applied[$version]),
                'applied_at' => $applied[$version] ?? null,
            ];
        }
        usort($rows, static fn(array $a, array $b): int => strcmp((string)$a['version'], (string)$b['version']));
        return $rows;
    }

    /** @return array<string,string|null> */
    private function appliedVersions(): array
    {
        try {
            $pdo = Database::connection();
            $pdo->exec('CREATE TABLE IF NOT EXISTS axiom_migrations (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, version VARCHAR(190) NOT NULL UNIQUE, batch INT NOT NULL DEFAULT 1, applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
            $stmt = $pdo->query('SELECT version, applied_at FROM axiom_migrations');
            $result = [];
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $result[(string)$row['version']] = $row['applied_at'] ?? null;
            }
            return $result;
        } catch (\Throwable) {
            return [];
        }
    }
}
