<?php

namespace App\Livewire;

use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Context\BranchContext;
use Livewire\Component;

class BranchSwitcher extends Component
{
    public string $selectedBranch = 'all';
    public bool $isPinned = false;

    /** Whether to offer the "كل الفروع" option at all. */
    public bool $canViewAll = false;

    /**
     * Purely a reader. Seeding the session is ResolveBranchContext's job now —
     * doing it here meant this method overwrote the "all branches" null with a
     * concrete branch on every render, so that mode could never be held.
     */
    public function mount(): void
    {
        $ctx = app(BranchContext::class);

        $this->isPinned = auth()->user()->preferred_branch_id !== null;
        $this->canViewAll = $ctx->canViewAllBranches();

        $branchId = $ctx->branchId();
        $this->selectedBranch = $branchId === null ? 'all' : (string) $branchId;
    }

    public function updatedSelectedBranch($value): void
    {
        $ctx = app(BranchContext::class);
        $user = auth()->user();

        if ($value === 'all') {
            // Offered only to users who may actually see every branch; guard
            // anyway so a crafted request cannot strand someone in a mode the
            // context would immediately repair.
            if (! $ctx->canViewAllBranches()) {
                return;
            }

            $ctx->set(null);
            $user->update(['preferred_branch_id' => null]);
            $this->isPinned = false;

            $target = route(config('branch_lock.redirect_route'));
        } else {
            $branchId = (int) $value;
            $ctx->set($branchId);
            $user->update(['preferred_branch_id' => $branchId]);
            $this->isPinned = true;

            $target = route('dashboard');
        }

        // Route on the new state rather than bouncing back via Referer — the
        // page they came from may no longer be reachable in the mode they just
        // entered.
        $this->redirect($target, navigate: true);
    }

    public function unpin(): void
    {
        auth()->user()->update(['preferred_branch_id' => null]);
        $this->isPinned = false;
    }

    public function pin(): void
    {
        if ($this->selectedBranch !== 'all') {
            auth()->user()->update(['preferred_branch_id' => (int) $this->selectedBranch]);
            $this->isPinned = true;
        }
    }

    public function render()
    {
        $ctx = app(BranchContext::class);

        return view('livewire.branch-switcher', [
            // Already loaded and cached for this request by the context.
            'branches' => $ctx->activeBranches(),
            'isLocked' => $ctx->isLocked(),
        ]);
    }
}
