<?php

namespace App\Services;

use App\Models\InventoryBalance;
use App\Models\Product;
use App\Models\ReplenishmentRule;
use Illuminate\Support\Collection;

class ReplenishmentService
{
    /**
     * Suggest transfer quantities from warehouse to store based on min/max rules.
     *
     * @return Collection<int, array{store_location_id:int, warehouse_location_id:int, product_id:int, suggested_qty:int}>
     */
    public function suggestions(?int $storeLocationId = null): Collection
    {
        $rules = ReplenishmentRule::query()
            ->where('is_active', true)
            ->when($storeLocationId, fn ($q) => $q->where('store_location_id', $storeLocationId))
            ->get();

        $suggestions = collect();

        foreach ($rules as $rule) {
            $productIds = $rule->product_id
                ? collect([$rule->product_id])
                : InventoryBalance::query()->where('location_id', $rule->store_location_id)->pluck('product_id');

            foreach ($productIds as $productId) {
                $storeBal = InventoryBalance::query()
                    ->where('location_id', $rule->store_location_id)
                    ->where('product_id', $productId)
                    ->first();

                $onHand = $storeBal?->on_hand ?? 0;
                if ($onHand > $rule->min_qty) {
                    continue;
                }

                $target = $rule->reorder_qty > 0 ? $rule->reorder_qty : max(0, $rule->max_qty - $onHand);
                if ($target <= 0) {
                    continue;
                }

                $whAvailable = InventoryBalance::query()
                    ->where('location_id', $rule->warehouse_location_id)
                    ->where('product_id', $productId)
                    ->first();

                $suggested = min($target, $whAvailable?->available() ?? 0);
                if ($suggested <= 0) {
                    continue;
                }

                $product = Product::query()->select('id', 'name', 'sku')->find($productId);

                $suggestions->push([
                    'store_location_id' => $rule->store_location_id,
                    'warehouse_location_id' => $rule->warehouse_location_id,
                    'product_id' => (int) $productId,
                    'product_name' => $product?->name ?? ('#' . $productId),
                    'product_sku' => $product?->sku,
                    'on_hand' => $onHand,
                    'warehouse_available' => $whAvailable?->available() ?? 0,
                    'suggested_qty' => $suggested,
                ]);
            }
        }

        return $suggestions->values();
    }
}
