<?php

namespace App\Services;

use App\Models\Product;
use App\Models\StockMovement;
use Illuminate\Support\Facades\DB;

class InventoryService
{
    public function getProducts()
    {
        return Product::all();
    }

    public function findProductByBarcode(string $barcode): ?Product
    {
        return Product::where('barcode', $barcode)->first();
    }

    public function increaseStock(int $productId, int $qty): Product
    {
        return DB::transaction(function () use ($productId, $qty) {
            $product = Product::lockForUpdate()->findOrFail($productId);
            $product->increment('stock', $qty);
            StockMovement::create([
                'product_id' => $product->id,
                'type' => 'purchase',
                'qty_change' => $qty,
            ]);
            return $product->fresh();
        });
    }

    public function decreaseStock(int $productId, int $qty): Product
    {
        return DB::transaction(function () use ($productId, $qty) {
            $product = Product::lockForUpdate()->findOrFail($productId);
            if ($product->stock < $qty) {
                throw new \Exception("Insufficient stock for product {$product->sku}");
            }
            $product->decrement('stock', $qty);
            StockMovement::create([
                'product_id' => $product->id,
                'type' => 'sale',
                'qty_change' => -$qty,
            ]);
            return $product->fresh();
        });
    }
}