<?php

namespace App\Domain\Shared\Traits;

use App\Domain\Identity\Models\Branch;

trait UsesBranchScope
{
    public function getActiveBranchId(): ?int
    {
        return session('active_branch_id', auth()->user()->branch_id);
    }

    public function getActiveBranchIdOrFail(): int
    {
        $id = $this->getActiveBranchId();

        if (!$id) {
            $id = Branch::where('is_active', true)->first()?->id;
            if ($id) {
                session(['active_branch_id' => $id]);
            }
        }

        return $id;
    }

    public function isAllBranches(): bool
    {
        return session('active_branch_id') === null && !session()->has('active_branch_id');
    }
}
