<?php

namespace App\Services\Admin;

use App\Models\ProductVariant;
use App\Models\StockHistory;
use Illuminate\Support\Facades\DB;

class InventoryService
{
    public function updateStock(
        int $variantId,
        int $quantity,
        string $type = 'adjustment',
        ?string $notes = null,
        ?int $userId = null,
        ?string $referenceType = null,
        ?int $referenceId = null
    ): ProductVariant {
        DB::beginTransaction();

        try {
            $variant = ProductVariant::findOrFail($variantId);
            $previousStock = $variant->stock_quantity;

            if ($type === 'in') {
                $variant->increment('stock_quantity', $quantity);
            } elseif ($type === 'out') {
                $variant->decrement('stock_quantity', $quantity);
            } else {
                $variant->stock_quantity = $quantity;
                $variant->save();
            }

            $newStock = $variant->fresh()->stock_quantity;

            StockHistory::log(
                $variantId,
                $type,
                $quantity,
                $previousStock,
                $newStock,
                $referenceType,
                $referenceId,
                $notes,
                $userId
            );

            DB::commit();

            return $variant->fresh();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function getStockHistory(int $variantId, int $limit = 50)
    {
        return StockHistory::with(['user', 'reference'])
            ->where('product_variant_id', $variantId)
            ->latest()
            ->limit($limit)
            ->get();
    }

    public function getLowStockProducts(int $threshold = null)
    {
        $query = ProductVariant::with('product')
            ->where('is_active', true);

        if ($threshold !== null) {
            $query->where('stock_quantity', '<=', $threshold);
        } else {
            $query->whereColumn('stock_quantity', '<=', 'min_stock_level');
        }

        return $query->orderBy('stock_quantity')->get();
    }
}
