<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\FavouriteRequest;
use App\Http\Resources\FavouriteResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class FavouriteController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $perPage = $request->query('per_page', 15);

        $favourites = $request->user()
            ->favourites()
            ->with('product.category')
            ->latest()
            ->paginate($perPage);

        return FavouriteResource::collection($favourites);
    }

    public function store(FavouriteRequest $request): FavouriteResource
    {
        $favourite = $request->user()->favourites()->create([
            'product_id' => $request->validated('product_id'),
        ]);

        $favourite->load('product.category');

        return new FavouriteResource($favourite);
    }

    public function destroy(Request $request, string $productId): JsonResponse
    {
        $deleted = $request->user()
            ->favourites()
            ->where('product_id', $productId)
            ->delete();

        if (! $deleted) {
            return response()->json([
                'message' => 'Favourite not found.',
            ], 404);
        }

        return response()->json([
            'message' => 'Product removed from favourites.',
        ]);
    }
}
