<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Artisan;

class UpgradeController extends Controller
{
    /**
     * Show the upgrade page if there are pending migrations.
     */
    public function index()
    {
        $pending = $this->getPendingMigrations();

        if (empty($pending)) {
            abort(404);
        }

        return view('upgrade.index', [
            'pendingMigrations' => $pending,
        ]);
    }

    /**
     * Run pending migrations and clear caches.
     */
    public function run()
    {
        $pending = $this->getPendingMigrations();

        if (empty($pending)) {
            return redirect('/');
        }

        // Run migrations
        Artisan::call('migrate', ['--force' => true]);

        // Clear all caches
        Artisan::call('optimize:clear');

        return redirect()->route('upgrade.completed');
    }

    /**
     * Show the upgrade completed page.
     */
    public function completed()
    {
        return view('upgrade.completed');
    }

    /**
     * Get list of pending migrations.
     */
    private function getPendingMigrations(): array
    {
        $migrator = app('migrator');

        // Get all migration files from the default path
        $files = $migrator->getMigrationFiles(database_path('migrations'));

        // Include plugin migrations (registered via AppServiceProvider)
        foreach ($migrator->paths() as $path) {
            $files = array_merge($files, $migrator->getMigrationFiles($path));
        }

        try {
            // Get already-run migrations from the database
            $ran = $migrator->getRepository()->getRan();
        } catch (\Exception $e) {
            // Database not accessible or migrations table doesn't exist
            return [];
        }

        // Return migration names that haven't been run yet
        $allMigrationNames = array_map(
            fn ($file) => pathinfo($file, PATHINFO_FILENAME),
            array_keys($files)
        );

        return array_values(array_diff($allMigrationNames, $ran));
    }
}
