<?php

namespace App\Http\Controllers\Api\V1\Favorite;

use App\Http\Controllers\Api\V1\Favorite\Requests\FavoriteStoreRequest;
use App\Http\Controllers\Api\V1\Favorite\Resources\FavoriteResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class FavoriteController extends Controller
{
    /**
     * (*) User's favorite products (index)
     */
    public function index(): JsonResponse
    {
        return response()->rest(
            FavoriteResource::collection(
                auth()->user()->favorites()->with(['product' => ['media', 'brand']])->get()
            )
        );
    }

    /**
     * (*) Store resource
     */
    public function store(FavoriteStoreRequest $request): JsonResponse
    {
        $data = auth()->user()->favorites()->where('product_id', $request->product_id)->first();

        $status = $data
                    ? $data->delete()
                    : auth()->user()->favorites()->create([
                        'user_id' => auth()->id(),
                        'product_id' => $request->product_id,
                    ]);

        return response()->rest(
            message: is_bool($status) ? 'Removed' : 'Added'
        );
    }
}
