<?php

namespace App\Http\Controllers\API\V1;

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

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

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

        return response()->json([
            'data' => FavouriteResource::collection(
                $favourites->load('product.category')
            ),
            'meta' => [
                'current_page' => $favourites->currentPage(),
                'per_page' => $favourites->perPage(),
                'total' => $favourites->total(),
                'last_page' => $favourites->lastPage(),
                'from' => $favourites->firstItem(),
                'to' => $favourites->lastItem(),
            ],
        ]);
    }

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

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

        return response()->json([
            'data' => FavouriteResource::make($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.',
        ]);
    }
}
