<?php

namespace App\Http\Controllers\Api\V1;

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

class FavoriteController extends Controller
{
    /** Liste des IDs des produits favoris (léger, pour vérifier un produit). */
    public function ids(Request $request): JsonResponse
    {
        $ids = $request->user()->favorites()->pluck('product_id');

        return response()->json(['data' => $ids->values()->all()]);
    }

    /** Liste des produits favoris (avec détails). */
    public function index(Request $request): JsonResponse
    {
        $favorites = $request->user()
            ->favorites()
            ->with(['product.category', 'product.productImages'])
            ->orderByDesc('created_at')
            ->get();
        $products = $favorites->map(fn ($f) => $f->product)->filter()->values();

        return response()->json([
            'data' => ProductResource::collection($products),
        ]);
    }

    /** Ajouter un produit aux favoris. */
    public function store(Request $request): JsonResponse
    {
        $request->validate(['product_id' => 'required|integer|exists:products,id']);

        $user = $request->user();
        $exists = $user->favorites()->where('product_id', $request->product_id)->exists();
        if ($exists) {
            return response()->json(['message' => __('Already in favorites.')], 200);
        }

        $user->favorites()->create(['product_id' => $request->product_id]);

        return response()->json(['message' => __('Added to favorites.')], 201);
    }

    /** Retirer un produit des favoris. */
    public function destroy(Request $request, Product $product): JsonResponse
    {
        $request->user()->favorites()->where('product_id', $product->id)->delete();

        return response()->json(['message' => __('Removed from favorites.')]);
    }
}
