<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\V1\Product\Resources\ProductResource;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Cart\CartRemoveRequest;
use App\Http\Requests\Api\V1\Cart\CartStoreRequest;
use Illuminate\Http\JsonResponse;

class CartController extends Controller
{
    /**
     * (*) Users carts (index)
     */
    public function index(): JsonResponse
    {
        $cartItems = auth()->user()->carts()
            ->with(['product' => ['media', 'brand', 'channels']])
            ->orderBy('cart_items.id', 'desc')
            ->get()
            ->each(function ($cartItem) {
                if ($cartItem->product->stock < $cartItem->product_quantity) {
                    if ($cartItem->product->stock >= 1) {
                        $cartItem->update([
                            'product_quantity' => $cartItem->product->stock,
                        ]);
                    } else {
                        $cartItem->delete();
                    }
                }
            });

        $data = $cartItems->map(fn ($cartItem) => [
            'id' => $cartItem->id,
            'user_id' => $cartItem->user_id,
            'product_id' => $cartItem->product_id,
            'product_quantity' => $cartItem->product_quantity,
            'created_at' => $cartItem->created_at,
            'updated_at' => $cartItem->updated_at,
            'product' => new ProductResource($cartItem->product),
        ])->groupBy(function (array $cartItem) {
            if (isset($cartItem['product']) && $cartItem['product']->channels->count() > 0) {
                return $cartItem['product']->channels[0]->slug;
            }

            return 'default';
        });

        return response()->rest(
            $data,
            code: 200,
            message: 'Cart items'
        );
    }

    /**
     * (*) Store new cart (store)
     */
    public function store(CartStoreRequest $request): JsonResponse
    {
        auth()->user()->carts()->updateOrInsert(
            ['user_id' => auth()->id(), 'product_id' => $request->product_id],
            ['product_quantity' => $request->product_quantity]
        );

        return response()->rest(message: 'Cart item added or updated successfully', code: 201);
    }

    /**
     * (*) Remove item from cart (patch)
     */
    public function remove(CartRemoveRequest $request): JsonResponse
    {
        auth()->user()->carts()->where('product_id', $request->product_id)->delete();

        return response()->rest(message: 'Cart item removed successfully', code: 200);
    }

    /**
     * (*) Delete all user's carts (delete)
     */
    public function destroy(): JsonResponse
    {
        auth()->user()->carts()->delete();

        return response()->rest(message: "All user's carts deleted successfully", code: 200);
    }
}
