<?php

namespace Modules\Bms\Services\Adapters\Erp;

use App\Utils\ProductUtil;
use Illuminate\Support\Facades\Log;
use Modules\Bms\Services\Contracts\StockServiceContract;

/**
 * ERP adapter for inventory movements. Moves real ERP stock between locations
 * via ProductUtil (which only acts on stock-enabled products — services and
 * unmapped items are safely skipped). Used by warehouse→hall transfers and
 * per-event consumable consumption.
 */
class ErpStockService implements StockServiceContract
{
    public function postEventConsumption(int $businessId, int $bookingId, array $lines): array
    {
        $pu = app(ProductUtil::class);
        $refs = [];

        foreach ($lines as $line) {
            if (empty($line['product_id']) || empty($line['variation_id']) || empty($line['location_id'])) {
                continue;
            }
            try {
                $pu->decreaseProductQuantity($line['product_id'], $line['variation_id'], $line['location_id'], (float) ($line['quantity'] ?? 0));
                $refs[] = ['product_id' => $line['product_id'], 'qty' => (float) ($line['quantity'] ?? 0), 'op' => 'consume'];
            } catch (\Throwable $e) {
                Log::warning('[BMS] stock consumption failed: ' . $e->getMessage());
            }
        }

        return $refs;
    }

    public function postTransfer(int $businessId, int $fromLocationId, int $toLocationId, array $lines, array $meta = []): ?int
    {
        $pu = app(ProductUtil::class);
        $refs = [];

        foreach ($lines as $line) {
            // Only mapped, stock-tracked products move ERP stock; assets / ad-hoc
            // items live in the BMS transfer record only.
            if (empty($line['product_id']) || empty($line['variation_id'])) {
                continue;
            }
            $qty = (float) ($line['quantity'] ?? 0);
            if ($qty <= 0) {
                continue;
            }
            try {
                $pu->decreaseProductQuantity($line['product_id'], $line['variation_id'], $fromLocationId, $qty);
                $pu->updateProductQuantity($toLocationId, $line['product_id'], $line['variation_id'], $qty, 0, null, false);
                $refs[] = ['product_id' => $line['product_id'], 'qty' => $qty, 'from' => $fromLocationId, 'to' => $toLocationId];
            } catch (\Throwable $e) {
                Log::warning('[BMS] stock transfer movement failed: ' . $e->getMessage());
            }
        }

        // Return the count of posted movements (0 = nothing stock-tracked moved).
        return count($refs);
    }
}
