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

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

class AdminProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $products = Product::with(['vendor:id,store_name', 'category:id,name'])
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%"))
            ->when($request->vendor_id, fn($q) => $q->where('vendor_id', $request->vendor_id))
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->when($request->category_id, fn($q) => $q->where('category_id', $request->category_id))
            ->latest()
            ->paginate(15);

        return response()->json($products);
    }

    public function show(int $id): JsonResponse
    {
        $product = Product::with(['vendor', 'category', 'reviews' => fn($q) => $q->with('user:id,name')->latest()->limit(10)])
            ->findOrFail($id);
        return response()->json(['product' => $product]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $product = Product::findOrFail($id);
        $data = $request->validate([
            'status'      => 'sometimes|in:draft,published,archived',
            'is_featured' => 'sometimes|boolean',
        ]);
        $product->update($data);
        return response()->json(['message' => 'Product updated.', 'product' => $product]);
    }

    public function destroy(int $id): JsonResponse
    {
        $product = Product::findOrFail($id);
        $product->delete();
        return response()->json(['message' => 'Product deleted.']);
    }

    public function store(Request $request): JsonResponse
    {
        return response()->json(['message' => 'Products are created by vendors.'], 405);
    }
}
