<?php

namespace App\Models\Concerns;

use App\Models\Tenant;
use App\Support\Tenancy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Hard tenant isolation at the ORM layer:
 *  - global scope filters every query by the current tenant
 *  - tenant_id is auto-filled on create
 * Covered by tests/Feature/TenancyIsolationTest.
 */
trait BelongsToTenant
{
    public static function bootBelongsToTenant(): void
    {
        static::addGlobalScope('tenant', function (Builder $builder) {
            $tenancy = app(Tenancy::class);
            if ($tenancy->check()) {
                $builder->where(
                    $builder->getModel()->getTable().'.tenant_id',
                    $tenancy->id()
                );
            }
        });

        static::creating(function (Model $model) {
            $tenancy = app(Tenancy::class);
            if ($tenancy->check() && empty($model->tenant_id)) {
                $model->tenant_id = $tenancy->id();
            }
        });
    }

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

    public function scopeWithoutTenancy(Builder $query): Builder
    {
        return $query->withoutGlobalScope('tenant');
    }
}
