<?php

namespace App\Models\Traits;

use App\Support\DealerContext;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

trait BelongsToDealer
{
    protected static function bootBelongsToDealer(): void
    {
        static::addGlobalScope('dealer_scope', function (Builder $builder): void {
            $dealerId = DealerContext::currentDealerId();

            if ($dealerId !== null) {
                $table = $builder->getModel()->getTable();
                $builder->where($table.'.dealer_id', $dealerId);
            }
        });

        static::creating(function (Model $model): void {
            $dealerId = DealerContext::currentDealerId();

            if ($dealerId !== null && empty($model->dealer_id)) {
                $model->dealer_id = $dealerId;
            }
        });
    }
}

