<?php

namespace App\Modules\Sales\Services;

use App\Modules\Inventory\Stock\Models\InventoryStockProjection;
use Illuminate\Support\Collection;

final class SalesOrderStockHintLookup
{
    /**
     * @param  Collection<int, \App\Modules\Sales\Models\SalesOrderLine>  $lines
     * @return array<string, string> key "{warehouse_id}_{item_id}" => available quantity string
     */
    public function availableByWarehouseItem(int $tenantId, Collection $lines): array
    {
        if ($lines->isEmpty()) {
            return [];
        }
        $q = InventoryStockProjection::withoutGlobalScopes()->where('tenant_id', $tenantId);
        $q->where(function ($outer) use ($lines): void {
            foreach ($lines as $line) {
                $outer->orWhere(function ($inner) use ($line): void {
                    $inner->where('warehouse_id', (int) $line->warehouse_id)
                        ->where('item_id', (int) $line->item_id);
                });
            }
        });
        $out = [];
        foreach ($q->get(['warehouse_id', 'item_id', 'available_quantity']) as $row) {
            $out[(int) $row->warehouse_id.'_'.(int) $row->item_id] = (string) $row->available_quantity;
        }

        return $out;
    }
}
