<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Models\WebsiteSetting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ResolveAcademyFromSlug
{
    public function handle(Request $request, Closure $next): Response
    {
        $slug = $request->route('slug');

        if (!$slug) {
            abort(404);
        }

        $academy = Academy::where('slug', $slug)
            ->where('status', 'active')
            ->first();

        if (!$academy) {
            abort(404);
        }

        $settings = WebsiteSetting::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->first();

        if (!$settings || !$settings->is_published) {
            abort(404);
        }

        app()->instance('current_academy', $academy);
        app()->instance('website_settings', $settings);

        return $next($request);
    }
}
