<?php

namespace App\Models\Concerns;

use App\Models\Central\Company;
use App\Models\Scopes\TenantScope;
use App\Tenancy\TenantManager;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Trait applied on every tenant-scoped Eloquent model.
 *  - Adds the global TenantScope so every query is filtered by company_id.
 *  - On create, auto-fills company_id from the current tenant.
 *  - Provides a `company()` relationship.
 */
trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function ($model) {
            if (empty($model->company_id)) {
                $tenant = app(TenantManager::class);
                if ($tenant->isResolved()) {
                    $model->company_id = $tenant->currentId();
                }
            }
        });
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }
}
