<?php

declare(strict_types=1);

namespace ImovelZapAi\Tenancy\Infrastructure\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use ImovelZapAi\Tenancy\Domain\Enums\TenantStatus;
use ImovelZapAi\Tenancy\Support\TenantContext;
use Symfony\Component\HttpFoundation\Response;

class EnsureTenantIsActive
{
    /** @var list<TenantStatus> */
    private const ALLOWED_STATUSES = [
        TenantStatus::Trial,
        TenantStatus::Active,
    ];

    public function handle(Request $request, Closure $next): Response
    {
        $tenantId = TenantContext::id();

        if ($tenantId === null) {
            return $next($request);
        }

        $tenant = $request->attributes->get('tenant');

        if ($tenant === null) {
            abort(404, 'Tenant not found.');
        }

        if (! in_array($tenant->status, self::ALLOWED_STATUSES, true)) {
            abort(403, 'Tenant is not active.');
        }

        return $next($request);
    }
}
