<?php

namespace App\Http\Middleware;

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

class UseSuperAdminSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->shouldUseSuperAdminSession($request)) {
            config(['session.cookie' => 'super_admin_session']);
        }

        return $next($request);
    }

    protected function shouldUseSuperAdminSession(Request $request): bool
    {
        if (Str::startsWith($request->path(), 'super-admin')) {
            return true;
        }

        $referer = $request->headers->get('referer');
        if (! $referer) {
            return false;
        }

        $refererPath = parse_url($referer, PHP_URL_PATH);

        return is_string($refererPath) && Str::startsWith(ltrim($refererPath, '/'), 'super-admin');
    }
}
