<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

$command = $argv[1] ?? 'help';
$options = array_slice($argv, 2);
$manager = migration_manager();

try {
    switch ($command) {
        case 'up':
            $ran = $manager->runPending();

            if ($ran === []) {
                echo "No pending migrations." . PHP_EOL;
                exit(0);
            }

            foreach ($ran as $migration) {
                echo "Migrated: {$migration}" . PHP_EOL;
            }

            echo 'Applied ' . count($ran) . ' migration(s).' . PHP_EOL;
            exit(0);

        case 'down':
            $steps = isset($argv[2]) ? max(1, (int) $argv[2]) : 1;
            $rolledBack = $manager->rollback($steps);

            if ($rolledBack === []) {
                echo "No applied migrations to roll back." . PHP_EOL;
                exit(0);
            }

            foreach ($rolledBack as $migration) {
                echo "Rolled back: {$migration}" . PHP_EOL;
            }

            echo 'Rolled back ' . count($rolledBack) . ' migration(s).' . PHP_EOL;
            exit(0);

        case 'status':
            $status = $manager->status();

            if ($status === []) {
                echo "No migration files found." . PHP_EOL;
                exit(0);
            }

            foreach ($status as $row) {
                $state = $row['ran'] ? 'up' : 'pending';
                $ranAt = $row['ran_at'] ?? '-';
                echo str_pad($state, 10) . ' ' . $row['migration'] . '  ' . $ranAt . PHP_EOL;
            }

            exit(0);

        case 'make':
        case 'create':
            $name = $argv[2] ?? '';

            if ($name === '') {
                throw new InvalidArgumentException('Provide a migration name. Example: php scripts/migrate.php make create_projects_table');
            }

            $path = $manager->make($name);
            echo "Created migration: {$path}" . PHP_EOL;
            exit(0);

        case 'fresh':
            $result = $manager->fresh();

            foreach ($result['rolled_back'] as $migration) {
                echo "Rolled back: {$migration}" . PHP_EOL;
            }

            foreach ($result['migrated'] as $migration) {
                echo "Migrated: {$migration}" . PHP_EOL;
            }

            echo "Fresh migration run complete." . PHP_EOL;
            exit(0);

        case 'help':
        default:
            echo "Migration CLI" . PHP_EOL;
            echo "Usage:" . PHP_EOL;
            echo "  php scripts/migrate.php up" . PHP_EOL;
            echo "  php scripts/migrate.php down [steps]" . PHP_EOL;
            echo "  php scripts/migrate.php status" . PHP_EOL;
            echo "  php scripts/migrate.php make <name>" . PHP_EOL;
            echo "  php scripts/migrate.php fresh [--seed]" . PHP_EOL;
            exit(0);
    }
} catch (Throwable $exception) {
    fwrite(STDERR, $exception->getMessage() . PHP_EOL);
    exit(1);
}
