<?php

namespace App\Services;

use App\Models\CartItem;
use App\Models\ProductVariant;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;

class CartService
{
    /**
     * Add or update an item in the cart.
     *
     * @throws ValidationException
     */
    public function addToCart(User $user, int $variantId, int $quantity): CartItem
    {
        $variant = ProductVariant::findOrFail($variantId);

        // Validate stock
        if ($variant->stock < $quantity) {
            throw ValidationException::withMessages([
                'quantity' => "Insufficient stock for variant '{$variant->name}'. Only {$variant->stock} left.",
            ]);
        }

        $cartItem = CartItem::updateOrCreate(
            [
                'user_id' => $user->id,
                'product_variant_id' => $variantId,
            ],
            [
                'quantity' => $quantity,
            ]
        );

        return $cartItem;
    }

    /**
     * Get cart items grouped by shop_id.
     */
    public function getCart(User $user): Collection
    {
        return CartItem::with(['variant.product.shop'])
            ->where('user_id', $user->id)
            ->get()
            ->groupBy(function ($item) {
                return $item->variant->product->shop_id;
            })
            ->map(function ($items, $shopId) {
                $firstItem = $items->first();
                $shop = $firstItem->variant->product->shop;

                return [
                    'shop_id' => $shopId,
                    'shop_name' => $shop ? $shop->name : 'Unknown Shop',
                    'items' => $items->map(function ($item) {
                        return [
                            'id' => $item->id,
                            'variant_id' => $item->product_variant_id,
                            'variant_name' => $item->variant->name,
                            'price' => $item->variant->price,
                            'quantity' => $item->quantity,
                            'stock' => $item->variant->stock,
                            'subtotal' => $item->variant->price * $item->quantity,
                        ];
                    }),
                ];
            })
            ->values();
    }
}
