<?php

namespace App\Models\Concerns;

use App\Models\Central\Tenant;
use App\Models\Scopes\TenantScope;
use App\Services\CurrentContext;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Models tagged with this trait automatically:
 *  - apply {@see TenantScope} (the hard tenant-isolation boundary)
 *  - default `tenant_id` on creating to the current tenant context
 *  - expose a `tenant()` relation
 *
 * Composes with {@see BranchScoped} and {@see Auditable}: tenant is the outer
 * boundary, branch the inner sub-divider. Trusted internal/landlord code bypasses
 * with `Model::withoutGlobalScope(TenantScope::class)` or `CurrentContext::runWithoutTenant()`.
 */
trait BelongsToTenant
{
    public static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function ($model): void {
            if ($model->tenant_id) {
                return;
            }

            $tenantId = app(CurrentContext::class)->tenantId();
            if ($tenantId) {
                $model->tenant_id = $tenantId;
            }
        });
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class, 'tenant_id');
    }
}
