<?php

namespace App\Models\Concerns;

use App\Models\Branch;
use App\Models\Scopes\BranchScope;
use App\Support\BranchContext;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Apply to any model that belongs to a branch.
 *
 * It (1) registers the global BranchScope so reads are auto-filtered, and
 * (2) stamps the active branch id on create when one is not supplied.
 */
trait BelongsToBranch
{
    public static function bootBelongsToBranch(): void
    {
        static::addGlobalScope(new BranchScope());

        static::creating(function ($model) {
            if (empty($model->{$model->getBranchColumn()})) {
                $branchId = app(BranchContext::class)->currentId();
                if ($branchId !== null) {
                    $model->{$model->getBranchColumn()} = $branchId;
                }
            }
        });
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, $this->getBranchColumn());
    }

    public function getBranchColumn(): string
    {
        return defined(static::class.'::BRANCH_COLUMN') ? static::BRANCH_COLUMN : 'branch_id';
    }

    public function getQualifiedBranchColumn(): string
    {
        return $this->getTable().'.'.$this->getBranchColumn();
    }

    /** Bypass branch scoping for a single query (use deliberately). */
    public function scopeAcrossBranches($query)
    {
        return $query->withoutGlobalScope(BranchScope::class);
    }
}
