<?php

namespace App\Traits;

use App\Models\Org;
use App\Models\Scopes\TenantScope;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

trait OrgRelated
{
    use SoftDeletes;

    public function orgs(): BelongsToMany
    {
        // Check if the model has a custom pivot model defined
        return $this->belongsToMany(Org::class);
    }

    /**
     * Get the custom pivot model class if defined.
     */
    protected function getOrgPivotModel(): ?string
    {
        return property_exists($this, 'orgPivotModel') ? $this->orgPivotModel : null;
    }

    public static function bootOrgRelated()
    {
        static::addGlobalScope(new TenantScope);
    }

    // Ensure user is attached to current tenant on creation
    protected static function booted()
    {
        static::creating(function ($model) {
            if (Auth::hasUser() && filament()->getTenant()) {
                // For many-to-many, we'll attach the tenant after creation
                static::created(function ($createdModel) {
                    if (Auth::hasUser() && filament()->getTenant()) {
                        $tenant = filament()->getTenant();
                        if (! $createdModel->orgs()->where('org_id', $tenant->id)->exists()) {
                            $createdModel->orgs()->attach($tenant);
                        }
                    }
                });
            }
        });
    }
}
