<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\Products\ProductResource;
use App\Models\Shop\Product\Product;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Maize\Markable\Models\Like;

class LikeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return response()->rest_paginate(ProductResource::collection(
            Product::with(['media', 'brand'])->whereHasLike(auth()->user())->paginate(15)
        ));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'product_id' => ['required', 'integer', 'exists:products,id'],
        ]);

        if ($validator->fails()) {
            return response()->rest($validator->messages()->get('*'), 400, 'Wrong credentials');
        }

        $product = Product::find($request->product_id);

        Like::add($product, auth()->user());

        return response()->rest([], 201);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'product_id' => ['required', 'integer', 'exists:products,id'],
        ]);

        if ($validator->fails()) {
            return response()->rest([], 400, 'Wrong credentials');
        }

        $product = Product::find($request->product_id);
        Like::remove($product, auth()->user());

        return response()->rest();
    }
}
