<?php
namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\App;
use LogicException;

trait BelongsToMerchant
{
    protected static function bootBelongsToMerchant(): void
    {
        static::creating(function ($model): void {
            if (empty($model->merchant_id) && App::bound('currentMerchant')) {
                $model->merchant_id = App::make('currentMerchant')->getKey();
            }
            if (empty($model->merchant_id)) {
                throw new LogicException('merchant_id is required for tenant-owned records.');
            }
        });
    }

    public function merchant(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Merchant::class);
    }

    public function scopeForMerchant(Builder $query, string|int $merchantId): Builder
    {
        return $query->where($query->getModel()->qualifyColumn('merchant_id'), $merchantId);
    }
}
