<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $items = $request->user()
            ->cartItems()
            ->with('product.category')
            ->get();

        $subtotal = $items->sum(fn (CartItem $item) => $item->product->price * $item->quantity);

        return response()->json([
            'data' => [
                'items' => $items->map(fn (CartItem $item) => [
                    'id' => $item->id,
                    'product_id' => $item->product_id,
                    'product' => [
                        'id' => $item->product->id,
                        'name' => $item->product->name,
                        'price' => (float) $item->product->price,
                        'image' => $item->product->image ? url('storage/' . $item->product->image) : null,
                    ],
                    'quantity' => $item->quantity,
                    'total' => round((float) $item->product->price * $item->quantity, 2),
                ]),
                'subtotal' => round($subtotal, 2),
            ],
        ]);
    }

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

        $product = Product::findOrFail($request->product_id);
        $item = CartItem::firstOrNew([
            'user_id' => $request->user()->id,
            'product_id' => $product->id,
        ]);
        $item->quantity = $item->exists ? $item->quantity + $request->quantity : $request->quantity;
        $item->save();

        $item->load('product');

        return response()->json([
            'data' => [
                'id' => $item->id,
                'product_id' => $item->product_id,
                'quantity' => $item->quantity,
            ],
            'message' => __('Added to cart.'),
        ], 201);
    }

    public function update(Request $request, CartItem $cartItem): JsonResponse
    {
        if ($cartItem->user_id !== $request->user()->id) {
            abort(404);
        }

        $request->validate(['quantity' => ['required', 'integer', 'min:1']]);
        $cartItem->update(['quantity' => $request->quantity]);

        return response()->json([
            'data' => ['id' => $cartItem->id, 'quantity' => $cartItem->quantity],
            'message' => __('Cart updated.'),
        ]);
    }

    public function destroy(Request $request, CartItem $cartItem): JsonResponse
    {
        if ($cartItem->user_id !== $request->user()->id) {
            abort(404);
        }
        $cartItem->delete();

        return response()->json(['message' => __('Removed from cart.')]);
    }
}
