<?php

namespace App\Domains\Cart\Controllers;

use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
use App\Domains\Cart\Resources\CartResource;
use App\Domains\Cart\Services\CartService;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function __construct(
        protected CartService $cartService,
    ) {
    }

    public function show(Request $request, Tenant $tenant): CartResource
    {
        return CartResource::make($this->cartService->show($tenant, $request));
    }

    public function addItem(AddCartItemRequest $request, Tenant $tenant): JsonResponse
    {
        $result = $this->cartService->addItem(
            $tenant,
            $request,
            (int) $request->validated('product_variant_id'),
            (int) $request->validated('cantidad'),
        );

        $response = CartResource::make($result['cart'])->response();

        if ($result['guest_token'] !== null) {
            $response->withCookie($this->cartService->makeGuestTokenCookie($result['guest_token']));
        }

        return $response;
    }

    public function updateItemQuantity(
        UpdateCartItemQuantityRequest $request,
        Tenant $tenant,
        ProductVariant $productVariant,
    ): CartResource {
        return CartResource::make(
            $this->cartService->updateItemQuantity(
                $tenant,
                $request,
                $productVariant->getKey(),
                (int) $request->validated('cantidad'),
            )
        );
    }

    public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource
    {
        return CartResource::make(
            $this->cartService->removeItem($tenant, $request, $productVariant->getKey())
        );
    }
}
