<?php

namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Builder;

trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::creating(function ($model) {
            if (! $model->tenant_id && app()->bound('tenant.id')) {
                $model->tenant_id = app('tenant.id');
            }
        });

        static::addGlobalScope('tenant', function (Builder $builder) {
            if (app()->bound('tenant.id')) {
                $builder->where($builder->getModel()->getTable() . '.tenant_id', app('tenant.id'));
            }
        });
    }
}
