<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LikeController extends Controller
{
    public function count()
    {
        return response()->json([
            'count' => auth()->user()->favorites()->count(),
        ]);
    }

    public function userLikes()
    {
        return response()->rest(
            auth()->user()->favorites()->with(['product' => ['media', 'brand']])->limit(4)->get()
                ->map(fn ($cartItem) => [
                    'id' => $cartItem->product->id,
                    'slug' => $cartItem->product->slug,
                    'name' => $cartItem->product->name,
                    'price_amount' => $cartItem->product->price_amount,
                    'brand_id' => $cartItem->product->brand_id,
                    'created_at' => $cartItem->product->created_at,
                    'brand' => $cartItem->product->brand,
                    'image' => $cartItem->product->thumbnail('200x200'),
                ]));
    }

    public function store(Request $request)
    {
        $request->validate([
            'id' => ['required', 'integer', 'exists:products,id'],
        ]);

        $data = auth()->user()->favorites()->where('product_id', $request->id)->first();

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

        return response()->json([
            'attached' => is_bool($status) ? false : true,
        ], 200);
    }

    public function clear()
    {
        DB::table('favorites')->where('user_id', auth()->id())->delete();

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