<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Models\Academy;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class SetCurrentAcademy
{
    public function handle(Request $request, Closure $next): Response
    {
        // A guest had no academy bound at all, so the login screen, the public
        // website and — once it exists — the member portal's own sign-in all
        // rendered under the fallback brand: the literal name "الكابتن" and the
        // stock blue, on every client.
        //
        // Every installation is one client with one academy, so when there is
        // exactly one it is unambiguous. More than one means a shared
        // installation where guessing would be wrong, and nothing is bound.
        if (! $request->user() && ! app()->has('current_academy')) {
            try {
                $sole = Cache::remember('academy:sole', 300, function () {
                    return Academy::query()->where('status', 'active')->count() === 1
                        ? Academy::query()->where('status', 'active')->first()?->id
                        : null;
                });

                if ($sole && $academy = Academy::find($sole)) {
                    app()->instance('current_academy', $academy);
                }
            } catch (\Throwable) {
                // Guest branding is a nicety. A database that is not reachable
                // — or not yet migrated — must not turn a 404 into a 500.
            }
        }

        if ($user = $request->user()) {
            // Load academy
            if ($user->academy_id) {
                $academy = Academy::find($user->academy_id);
                app()->instance('current_academy', $academy);
            }

            // Eager-load role with permissions for permission checks
            if ($user->role_id && !$user->relationLoaded('primaryRole')) {
                $user->load('primaryRole.permissions');
            } elseif (!$user->role_id && !$user->relationLoaded('roles')) {
                $user->load('roles.permissions');
            }
        }

        return $next($request);
    }
}
