<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfInstalled
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->isInstalled()) {
            return redirect('/login'); // or home page
        }

        return $next($request);
    }

    private function isInstalled(): bool
    {
        try {
            // Ensure migrations table exists AND at least one user exists
            return Schema::hasTable('users') && User::count() > 0;
        } catch (\Throwable $e) {
            return false;
        }
    }
}
