<?php

namespace App\Models\Concerns;

use App\Models\Branch;
use App\Models\Scopes\BranchScope;
use App\Services\CurrentContext;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;

/**
 * Models tagged with this trait automatically:
 *  - apply BranchScope (filters queries to the current branch context)
 *  - default branch_id on creating to the current context branch
 *  - expose a branch() relation pointing at Branch (UI-labelled "Branch")
 *
 * Full admins see all branches; everyone else is limited to the branches in
 * their access list — including in the "All branches" aggregate mode. Trusted
 * internal code can bypass with `Model::withoutGlobalScope(BranchScope::class)`.
 */
trait BranchScoped
{
    public static function bootBranchScoped(): void
    {
        static::addGlobalScope(new BranchScope);

        static::creating(function ($model): void {
            if (! Auth::check() || $model->branch_id) {
                return;
            }

            $branchId = app(CurrentContext::class)->branchId();
            if ($branchId) {
                $model->branch_id = $branchId;
            }
        });
    }

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