<?php

namespace App\Http\Controllers\Concerns;

use App\Services\CurrentContext;
use Illuminate\Http\Request;

/**
 * Shared branch-view resolution for dashboards and reports.
 *
 * Reads the `?branch_id` parameter and points CurrentContext at either a
 * concrete branch (scoped views) or the "All branches" aggregate. Returns the
 * resolved branch id, or null for "All" — pass it to
 * Product::withStockFor($branchId) for stock aggregation.
 *
 * Default (no/blank/"all" param) is the All aggregate. Invalid or inaccessible
 * ids also fall back to All.
 */
trait ResolvesBranchFilter
{
    protected function resolveBranchFilter(Request $request): ?int
    {
        $context = app(CurrentContext::class);
        $param = $request->query('branch_id');

        // No param: keep whatever ResolveBranchContext resolved from the
        // session (top-bar selector / lone branch / aggregate).
        if ($param === null || $param === '') {
            return $context->branchId();
        }

        // A concrete branch is honoured only when the user can access it;
        // anything else (including "all") falls back to the aggregate, which
        // BranchScope still limits to the user's accessible branches.
        if ($param !== 'all' && $context->canAccessBranch((int) $param)) {
            $context->setBranch((int) $param);

            return (int) $param;
        }

        $context->setAllBranches();

        return null;
    }

    /**
     * Branch-selector payload for the page: the list of branches, the resolved
     * selection ('all' or an id), and whether to render the control at all
     * (only when more than one active branch exists).
     *
     * @return array{branches: array<int, array{id:int, name:string}>, selected: int|string, show_selector: bool}
     */
    protected function branchViewProps(?int $branchId): array
    {
        $context = app(CurrentContext::class);
        $branches = $context->branches();

        return [
            'branches' => $branches->map(fn ($b) => ['id' => $b->id, 'name' => $b->name])->values()->all(),
            'selected' => $branchId ?? 'all',
            'show_selector' => $branches->count() > 1,
        ];
    }
}
