<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

/**
 * Adds automatic per-organization data isolation to an Eloquent model.
 *
 * Every SELECT is scoped to the current tenant (resolved from the IoC container).
 * Every INSERT auto-fills organization_id from the same container binding.
 *
 * The scope is intentionally a no-op when no tenant is bound, so that:
 *  - Sanctum's internal user lookup (before auth) is unaffected.
 *  - Password-reset flows that query by email work globally.
 *  - Artisan commands without a tenant context don't break.
 */
trait BelongsToOrganization
{
    protected static function bootBelongsToOrganization(): void
    {
        // --- Global query scope -------------------------------------------
        static::addGlobalScope('organization', function (Builder $builder) {
            if (app()->bound('current_organization_id')) {
                $builder->where(
                    $builder->getModel()->getTable() . '.organization_id',
                    app('current_organization_id')
                );
            }
        });

        // --- Auto-fill on create ------------------------------------------
        static::creating(function ($model) {
            if (
                app()->bound('current_organization_id') &&
                empty($model->organization_id)
            ) {
                $model->organization_id = app('current_organization_id');
            }
        });
    }

    /**
     * Escape hatch: query across all organizations (super-admin use).
     */
    public static function withoutOrganizationScope(): Builder
    {
        return static::withoutGlobalScope('organization');
    }

    public function organization()
    {
        return $this->belongsTo(\App\Models\Organization::class);
    }
}
