<?php

namespace Mtc\Plugins\Consumables\Classes;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mtc\Plugins\Consumables\Models\ItemConsumable;

class ConsumableStockService
{
    /**
     * Deduct consumable stock for all items in a paid order.
     *
     * Called via OrderPaidEvent listener, after the core deductStock()
     * has already decremented the main product stock.
     */
    public function deductForOrder(\Order $order): void
    {
        $orderItems = $order->getItems();

        if (empty($orderItems)) {
            return;
        }

        // Collect item IDs from the order
        $itemIds = array_unique(array_column($orderItems, 'item_id'));

        // Batch-load all consumable mappings for items in this order
        $consumables = ItemConsumable::whereIn('item_id', $itemIds)->get();

        if ($consumables->isEmpty()) {
            return;
        }

        // Group consumables by item_id for fast lookup
        $grouped = $consumables->groupBy('item_id');

        // Calculate total consumable deductions (a consumable may be linked to multiple order items)
        $deductions = [];
        foreach ($orderItems as $orderItem) {
            $itemId = $orderItem['item_id'];
            $orderQty = (int) $orderItem['quantity'];

            if (!isset($grouped[$itemId])) {
                continue;
            }

            foreach ($grouped[$itemId] as $consumable) {
                $consumableId = $consumable->consumable_item_id;
                $deductQty = $consumable->quantity * $orderQty;

                if (!isset($deductions[$consumableId])) {
                    $deductions[$consumableId] = 0;
                }
                $deductions[$consumableId] += $deductQty;
            }
        }

        // Apply deductions in a single transaction
        if (!empty($deductions)) {
            DB::transaction(function () use ($deductions) {
                foreach ($deductions as $consumableItemId => $totalDeduct) {
                    \Mtc\Shop\Item::where('id', $consumableItemId)
                        ->decrement('stock', $totalDeduct);
                }
            });

            Log::channel('single')->info('Consumable stock deducted', [
                'deductions' => $deductions,
            ]);
        }
    }
}
