<?php

namespace App\Domains\Cart\Controllers;

use App\Domains\Cart\Models\CartItem;
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\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('catalog_item_id'),
            $request->validated('variant_id') !== null
                ? (int) $request->validated('variant_id')
                : null,
            (int) $request->validated('cantidad'),
        );

        $response = CartResource::make($result['cart'])
            ->additional([
                'code' => 'cart.item_added',
                'message' => __('api.cart.item_added'),
            ])
            ->response();

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

        return $response;
    }

    public function updateItemQuantity(
        UpdateCartItemQuantityRequest $request,
        Tenant $tenant,
        CartItem $cartItem,
    ): CartResource {
        $updatesVariant = $request->exists('variant_id');

        return CartResource::make(
            $this->cartService->updateItem(
                $tenant,
                $request,
                $cartItem->getKey(),
                (int) $request->validated('cantidad'),
                $updatesVariant
                    ? ($request->validated('variant_id') !== null
                        ? (int) $request->validated('variant_id')
                        : null)
                    : $cartItem->variant_id,
                $updatesVariant,
            )
        )->additional([
            'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
            'message' => $updatesVariant
                ? __('api.cart.item_updated')
                : __('api.cart.quantity_updated'),
        ]);
    }

    public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
    {
        return CartResource::make(
            $this->cartService->removeItem($tenant, $request, $cartItem->getKey())
        )->additional([
            'code' => 'cart.item_removed',
            'message' => __('api.cart.item_removed'),
        ]);
    }
}
