<?php

namespace App\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Http\Request;

class TenantScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model)
    {

        // artisan migrate 등은 제외
        if (app()->runningInConsole()) {
            return;
        }

        // request 헬퍼 사용 → request 인스턴스를 명시적으로 주입받아 사용해야 함
        $request = app(Request::class);

        $tenantId = $request->attributes->get('tenant_id')
            ?? $request->header('X-TENANT-ID')
            ?? auth()->user()?->tenant_id;

        if ($tenantId !== null) {
            $builder->where($model->getTable().'.tenant_id', $tenantId);
        }
    }
}
