<?php

namespace App\Domain\Shared\Traits;

use App\Domain\Identity\Models\Branch;

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

        return session('active_branch_id');
    }

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

        if (!$id) {
            $branch = Branch::where('is_active', true)->first()
                ?? Branch::withoutGlobalScopes()->where('is_active', true)->first();

            if ($branch) {
                $id = $branch->id;
                session(['active_branch_id' => $id]);
            } else {
                abort(403, 'لا يوجد فرع نشط. يرجى إنشاء فرع أولاً.');
            }
        }

        return $id;
    }

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