<?php

namespace App\View\Composers;

use App\Services\LocationService;
use Illuminate\View\View;

class AdminLayoutComposer
{
    public function __construct(protected LocationService $locationService)
    {
    }

    public function compose(View $view): void
    {
        $user = auth()->user();
        if (!$user) {
            $view->with([
                'adminAccessibleLocations' => collect(),
                'adminCurrentLocation' => null,
                'adminCatalogueWritable' => false,
                'adminCentralWarehouseId' => null,
            ]);

            return;
        }

        $locations = $this->locationService->accessibleLocations($user);
        $currentId = $this->locationService->resolveLocationIdForUser($user);

        // Prefer collection match, then direct session/DB lookup (avoids type/id mismatch).
        $current = null;
        if ($currentId) {
            $current = $locations->first(fn ($loc) => (int) $loc->id === (int) $currentId)
                ?? $this->locationService->currentLocation()
                ?? \App\Models\Location::query()->find($currentId);
        }

        $view->with([
            'adminAccessibleLocations' => $locations,
            'adminCurrentLocation' => $current,
            'adminCatalogueWritable' => $this->locationService->catalogueWritableForUser($user),
            'adminCentralWarehouseId' => $this->locationService->centralWarehouse()?->id,
        ]);
    }
}