<?php

declare(strict_types=1);

namespace App\Business\Purchase;

use App\Business\Inventory\InventoryRuleService;
use App\Models\DberpPurchaseOrder;

final class PurchaseOrderRequestedWarehouseResolver
{
    /**
     * @return list<int>
     */
    public function distinctRequestedWarehouseIds(DberpPurchaseOrder $order): array
    {
        return $order->items()
            ->whereNotNull('requested_warehouse_id')
            ->distinct()
            ->orderBy('requested_warehouse_id')
            ->pluck('requested_warehouse_id')
            ->map(fn (mixed $id): int => (int) $id)
            ->values()
            ->all();
    }

    public function hasMixedRequestedWarehouses(DberpPurchaseOrder $order): bool
    {
        return count($this->distinctRequestedWarehouseIds($order)) > 1;
    }

    public function resolveDefaultReceiptWarehouseId(DberpPurchaseOrder $order): ?int
    {
        $warehouseIds = $this->distinctRequestedWarehouseIds($order);

        if (count($warehouseIds) === 1) {
            return $warehouseIds[0];
        }

        return app(InventoryRuleService::class)->defaultWarehouseId();
    }
}
