<?php
namespace App\Http\Controllers\API\Vendor;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VendorInventoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $vendorId = $request->user()->vendor->id;
        $products = Product::where('vendor_id', $vendorId)->where('track_inventory', true)
            ->when($request->low_stock, fn($q) => $q->whereColumn('stock_quantity', '<=', 'low_stock_threshold'))
            ->select('id', 'name', 'sku', 'stock_quantity', 'low_stock_threshold', 'stock_status', 'price', 'thumbnail')
            ->latest()->paginate(20);
        return response()->json($products);
    }
    public function update(Request $request, int $productId): JsonResponse
    {
        $product = Product::where('vendor_id', $request->user()->vendor->id)->findOrFail($productId);
        $data = $request->validate(['stock_quantity' => 'required|integer|min:0', 'low_stock_threshold' => 'integer|min:0']);
        $data['stock_status'] = $data['stock_quantity'] > 0 ? 'in_stock' : 'out_of_stock';
        $product->update($data);
        return response()->json(['message' => 'Inventory updated.', 'product' => $product]);
    }
}
