#!/usr/bin/env php
<?php

/**
 * Create a migration using the project convention.
 * Usage: php bin/make-migration descripcion_en_snake_case [--dry-run]
 */

$basePath = dirname(__DIR__);
$slug = strtolower(trim($argv[1] ?? ''));
$dryRun = in_array('--dry-run', $argv, true);

if (!preg_match('/^[a-z0-9]+(?:_[a-z0-9]+)*$/', $slug)) {
    fwrite(STDERR, "Usage: php bin/make-migration descripcion_en_snake_case [--dry-run]\n");
    exit(1);
}

$filename = date('Y_m_d_His') . '_' . $slug . '.php';
$target = $basePath . '/database/migrations/' . $filename;
$template = "<?php\n\n/**\n * Migration: {$slug}\n *\n * Keep reference and demo data in seeders. If a data correction is unavoidable,\n * document why it belongs here and provide a safe rollback or backup plan.\n */\nreturn array(\n    'up' => function (PDO \$pdo): void {\n        throw new \\LogicException('Implement migration up() before executing it.');\n    },\n    'down' => function (PDO \$pdo): void {\n        throw new \\LogicException('Implement migration down() before executing it.');\n    },\n);\n";

if ($dryRun) {
    echo "Would create: {$target}\n\n{$template}";
    exit(0);
}

if (file_exists($target)) {
    fwrite(STDERR, "Migration already exists: {$target}\n");
    exit(1);
}

if (file_put_contents($target, $template) === false) {
    fwrite(STDERR, "Unable to create migration: {$target}\n");
    exit(1);
}

echo "Created migration: {$target}\n";
