<?php

namespace App\Services;

use App\Models\InventoryMovement;
use App\Models\ProductVariant;
use App\Models\User;
use Illuminate\Support\Facades\DB;

/**
 * The admin-facing counterpart to the automatic stock changes Steps 10
 * (order placed) and 12 (order cancelled) already make — manual
 * corrections (restocking, miscount fixes) go through here so they get
 * the same InventoryMovement audit trail rather than a silent update.
 */
class InventoryService
{
    public function adjust(ProductVariant $variant, int $newQuantity, ?int $lowStockThreshold, ?string $reason, User $admin): void
    {
        $inventory = $variant->inventory;
        $delta = $newQuantity - $inventory->quantity;

        DB::transaction(function () use ($inventory, $variant, $delta, $newQuantity, $lowStockThreshold, $reason, $admin) {
            $inventory->update([
                'quantity' => $newQuantity,
                'low_stock_threshold' => $lowStockThreshold ?? $inventory->low_stock_threshold,
            ]);

            if ($delta !== 0) {
                InventoryMovement::create([
                    'product_variant_id' => $variant->id,
                    'type' => 'adjustment',
                    'quantity' => $delta,
                    'reason' => $reason ?: 'Manual stock adjustment',
                    'created_by' => $admin->id,
                ]);
            }
        });
    }
}
