<?php

namespace App\Domains\Purchase\Exceptions;

use RuntimeException;

class InsufficientStockException extends RuntimeException
{
    /**
     * @param  array<int, array{
     *     index: int,
     *     catalog_item_id: int,
     *     variant_id: int|null,
     *     requested_quantity: int,
     *     available_quantity: int,
     *     message: string
     * }>  $unavailableItems
     */
    public function __construct(
        public readonly array $unavailableItems,
    ) {
        parent::__construct(
            collect($unavailableItems)->pluck('message')->unique()->implode(' '),
        );
    }

    /** @return array<string, array<int, string>> */
    public function errors(): array
    {
        return collect($this->unavailableItems)
            ->mapWithKeys(fn (array $item): array => [
                "direct_items.{$item['index']}.cantidad" => [$item['message']],
            ])
            ->all();
    }
}
