#!/usr/bin/env php
<?php
// Run: php scripts/verify-fk-order.php
// Scans all migrations in order, tracks table creation, flags any FK to a table not yet created.

$migrationsPath = __DIR__ . '/../database/migrations';
$files = glob($migrationsPath . '/*.php');
sort($files); // chronological order

$createdTables = ['users', 'password_reset_tokens', 'sessions', 'cache', 'cache_locks', 'jobs', 'job_batches', 'failed_jobs'];
$errors = [];

foreach ($files as $file) {
    $content = file_get_contents($file);
    $basename = basename($file);

    // Track table creation
    if (preg_match_all('/Schema::create\([\'"](\w+)[\'"]/', $content, $creates)) {
        foreach ($creates[1] as $table) {
            $createdTables[] = $table;
        }
    }

    // Check FK references via constrained('table')
    if (preg_match_all('/->constrained\([\'"](\w+)[\'"]/', $content, $constrained)) {
        foreach ($constrained[1] as $refTable) {
            if (!in_array($refTable, $createdTables)) {
                $errors[] = "[{$basename}] FK references '{$refTable}' which has not been created yet.";
            }
        }
    }

    // Check references()->on() style
    if (preg_match_all('/->references\([\'"]id[\'"]\)->on\([\'"](\w+)[\'"]/', $content, $refs)) {
        foreach ($refs[1] as $refTable) {
            if (!in_array($refTable, $createdTables)) {
                $errors[] = "[{$basename}] FK references '{$refTable}' which has not been created yet.";
            }
        }
    }

    // Check foreignId()->constrained() (no explicit table — infers from column name)
    if (preg_match_all('/foreignId\([\'"](\w+)_id[\'"]\)->constrained\(\)/', $content, $implicit)) {
        foreach ($implicit[1] as $singular) {
            // Laravel pluralizes the table name from the column
            $inferredTable = $singular . 's';
            // Handle common irregular plurals
            $irregulars = [
                'facility' => 'facilities',
                'activity' => 'activities',
                'category' => 'categories',
                'inventory' => 'inventories',
                'company' => 'companies',
                'academy' => 'academies',
                'currency' => 'currencies',
                'history' => 'histories',
            ];
            if (isset($irregulars[$singular])) {
                $inferredTable = $irregulars[$singular];
            }
            if (!in_array($inferredTable, $createdTables)) {
                $errors[] = "[{$basename}] implicit FK '{$singular}_id' expects table '{$inferredTable}' which has not been created yet.";
            }
        }
    }
}

if (empty($errors)) {
    echo "\033[32m✓ All FK references point to existing tables.\033[0m\n";
    echo "  Tables tracked: " . count($createdTables) . "\n";
    exit(0);
} else {
    echo "\033[31mFK ORDER ERRORS:\033[0m\n";
    foreach ($errors as $e) {
        echo "  \033[33m- {$e}\033[0m\n";
    }
    echo "\n  Total errors: " . count($errors) . "\n";
    exit(1);
}
