<?php
require __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\ConnectionManager;

$tenant = $argv[1] ?? 'default';
$dir = __DIR__ . '/../modules/Financeiro/migrations';
if (!is_dir($dir)) { fwrite(STDERR, "Migrations dir not found: $dir\n"); exit(1); }

$files = array_values(array_filter(scandir($dir), function($f){ return preg_match('/\.sql$/', $f); }));
sort($files, SORT_NATURAL);
if (empty($files)) { fwrite(STDERR, "No .sql migrations found in $dir\n"); exit(1); }

$pdo = ConnectionManager::forTenant($tenant);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

foreach ($files as $f) {
    $path = $dir . '/' . $f;
    $sql = file_get_contents($path);
    if ($sql === false) { fwrite(STDERR, "Failed to read $path\n"); exit(1); }
    echo "Applying: $f\n";
    try {
        $pdo->exec($sql);
        echo "OK: $f\n";
    } catch (Throwable $e) {
        fwrite(STDERR, "Error applying $f: " . $e->getMessage() . "\n");
        exit(1);
    }
}

echo "Done.\n";