<?php

namespace App\Modules\Admin\Tenancy\Scopes;

use App\Models\User;
use App\Modules\Admin\Tenancy\Services\TenantContext;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        /** @var TenantContext|null $ctx */
        $ctx = app()->bound(TenantContext::class) ? app(TenantContext::class) : null;
        if ($ctx?->hasTenant()) {
            $builder->where($model->getTable().'.tenant_id', $ctx->tenantId());
            return;
        }

        $user = auth()->user();
        if (! $user instanceof User) {
            // No auth + no explicit tenant context: deny by default to prevent cross-tenant leakage
            // (e.g. queue/CLI accidentally querying tenant-scoped models).
            $builder->whereRaw('1 = 0');
            return;
        }
        if ($user->isAdmin()) {
            return;
        }
        if ($user->tenant_id === null) {
            $builder->whereRaw('1 = 0');
            return;
        }

        $builder->where($model->getTable().'.tenant_id', $user->tenant_id);
    }
}

