<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfInstalled
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->isInstalled()
            && !$request->routeIs('install.setup.finished')
            && !$request->routeIs('invalid.purchase')
            && !$request->routeIs('verify.puchase')) {

            return redirect()->route('auth.login')->with('success', trans('default.already_installed'));
        }

        return $next($request);
    }

    protected function isInstalled(): bool
    {
        try {
            // Use consistent installation check logic
            $logFile = storage_path(base64_decode(config('installer.cacheFile', base64_encode('installed'))));

            // Check multiple conditions for proper installation
            return env('APP_INSTALL', false) === 'true' ||
                   env('APP_INSTALL', false) === true ||
                   file_exists($logFile) ||
                   file_exists(storage_path('installed.lock'));
        } catch (\Exception $e) {
            return false;
        }
    }
}
