<?php

namespace App\Modules\Admin\Tenancy\Traits;

use App\Models\User;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Scopes\TenantScope;
use App\Modules\Admin\Tenancy\Services\TenantContext;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @mixin Model
 */
trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope());

        static::creating(function (Model $model): void {
            if ($model->getAttribute('tenant_id') !== null) {
                return;
            }

            /** @var TenantContext|null $ctx */
            $ctx = app()->bound(TenantContext::class) ? app(TenantContext::class) : null;
            if ($ctx?->hasTenant()) {
                $model->setAttribute('tenant_id', $ctx->tenantId());
                return;
            }

            $user = auth()->user();
            if (! $user instanceof User || $user->isAdmin() || $user->tenant_id === null) {
                return;
            }
            $model->setAttribute('tenant_id', $user->tenant_id);
        });
    }

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

