<?php

namespace App\Http\Middleware;

use App\Enums\UserStatus;
use App\Exceptions\DomainException;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserActive
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user || $user->status !== UserStatus::ACTIVE || ! $user->organization?->is_active) {
            if ($user?->currentAccessToken()) {
                $user->currentAccessToken()->delete();
            }

            throw new DomainException(
                'ACCOUNT_DISABLED',
                'This account is disabled or the organization is inactive.',
                403
            );
        }

        return $next($request);
    }
}
