<?php

namespace App\Http\Middleware;

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

class EnsureBrandAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if user is authenticated
        if (!auth()->check()) {
            return redirect()->route('login');
        }
        
        // Check if user has brand_admin role
        if (!auth()->user()->hasRole('brand_admin')) {
            // If user is a superadmin, allow access
            if (auth()->user()->hasRole('superadmin')) {
                return $next($request);
            }
            
            // Redirect to appropriate dashboard based on user role
            if (auth()->user()->hasRole('creator')) {
                return redirect()->route('creator.dashboard');
            } elseif (auth()->user()->hasRole('agency')) {
                return redirect()->route('agency.dashboard');
            }
            
            // For other roles, redirect to home
            return redirect('/');
        }
        
        // Check if user has a brand
        if (!auth()->user()->brand) {
            return response()->view('errors.brand-not-found', [], 404);
        }
        
        return $next($request);
    }
}