<?php
namespace Core\Database;

use Exception;

class MigrationHistory
{
    private static string $file = STORAGE_PATH . DIRECTORY_SEPARATOR . 'migrationsLog' . DIRECTORY_SEPARATOR . 'migrations.bin';

    /**
     * Store a new migration record
     */
    public static function record(array $data): void
    {
        $history = self::loadAll();
        $id = count($history) + 1;

        $data['id'] = $id;
        $data['timestamp'] = date('Y-m-d H:i:s');

        $history[] = $data;

        // Save compressed binary
        if (file_put_contents(self::$file, gzcompress(serialize($history))) === false) {
            throw new Exception("Failed to write migration history.");
        }
    }

    /**
     * Load all migrations
     */
    public static function loadAll(): array
    {
        if (!file_exists(self::$file)) {
            return [];
        }

        $content = file_get_contents(self::$file);
        return $content ? unserialize(gzuncompress($content)) : [];
    }

    /**
     * Find migration by ID
     */
    public static function find(int $id): ?array
    {
        $history = self::loadAll();
        foreach ($history as $record) {
            if ($record['id'] === $id) {
                return $record;
            }
        }
        return null;
    }

    /**
     * Update a migration record by ID
     */
    public static function update(int $id, array $newData): void
    {
        $history = self::loadAll();
        foreach ($history as &$record) {
            if ($record['id'] === $id) {
                $record = array_merge($record, $newData);
                break;
            }
        }
        if (file_put_contents(self::$file, gzcompress(serialize($history))) === false) {
            throw new Exception("Failed to update migration history.");
        }
    }
}
