<?php

namespace App\Http\Middleware;

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

class ServiceAdminRestrict
{
    /**
     * Restrict service_admin to Support (customer service) routes only.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $role = $request->session()->get('admin.role');

        if ($role !== 'service_admin') {
            return $next($request);
        }

        $routeName = $request->route()?->getName() ?? '';

        $allowed = [
            'admin.support',
            'admin.set-locale',
        ];

        foreach ($allowed as $prefix) {
            if ($routeName === $prefix || str_starts_with($routeName, $prefix . '.')) {
                return $next($request);
            }
        }

        return redirect()->route('admin.support');
    }
}
