<?php

namespace App\Http\Middleware;

use App\Models\Org;
use Closure;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasAssociation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();
        $tenant = Filament::getTenant();

        if (! $user || ! $tenant instanceof Org) {
            return redirect()->route('filament.admin.auth.login');
        }

        // Check if user has an association in the current organization
        if (! $user->hasAssociationInOrg($tenant)) {
            // Redirect to admin panel if user doesn't have an association
            return redirect()->route('filament.admin.pages.dashboard');
        }

        return $next($request);
    }
}
