<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Shop;

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

class CartController extends Controller
{
    public function __construct(private readonly CartService $service) {}

    public function show(Request $request): JsonResponse
    {
        $cart = $this->service->resolveCart($request);
        return response()->json(['data' => $this->service->summary($cart)]);
    }

    public function addItem(Request $request): JsonResponse
    {
        $data = $request->validate([
            'product_id' => ['required', 'uuid'],
            'variant_id' => ['nullable', 'uuid'],
            'qty' => ['nullable', 'integer', 'min:1', 'max:99'],
        ]);
        $product = Product::findOrFail($data['product_id']);
        if ($product->status !== 'active') {
            return response()->json(['error' => 'PRODUCT_UNAVAILABLE'], 422);
        }

        $cart = $this->service->resolveCart($request);
        $item = $this->service->addItem($cart, $data['product_id'], $data['variant_id'] ?? null, (int) ($data['qty'] ?? 1));
        return response()->json(['data' => $item, 'summary' => $this->service->summary($cart)], 201);
    }

    public function updateItem(Request $request, string $id): JsonResponse
    {
        $cart = $this->service->resolveCart($request);
        $item = CartItem::where('cart_id', $cart->id)->where('id', $id)->firstOrFail();
        $data = $request->validate(['qty' => ['required', 'integer', 'min:1', 'max:99']]);
        $item->qty = (int) $data['qty'];
        $item->save();
        return response()->json(['data' => $item, 'summary' => $this->service->summary($cart)]);
    }

    public function removeItem(Request $request, string $id): JsonResponse
    {
        $cart = $this->service->resolveCart($request);
        CartItem::where('cart_id', $cart->id)->where('id', $id)->delete();
        return response()->json(['data' => ['id' => $id, 'deleted' => true], 'summary' => $this->service->summary($cart)]);
    }
}
