<?php

namespace App\Http\Controllers;

use App\Http\Requests\CartItemRequest;
use App\Http\Resources\CartItemResource;
use App\Services\CartItemService;
use Illuminate\Http\JsonResponse;

class CartItemController extends Controller
{
    public function __construct(
        protected CartItemService $service,
    ) {}

    public function index(): JsonResponse
    {
        $items = $this->service->getAll();

        return $this->successResponse(payload: CartItemResource::collection($items));
    }

    public function store(CartItemRequest $request): JsonResponse
    {
        $item = $this->service->create($request->validated());

        return $this->successResponse(payload: new CartItemResource($item), message: __('messages.created'), code: 201);
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->service->findById($id);

        return $this->successResponse(payload: new CartItemResource($item));
    }

    public function update(CartItemRequest $request, int $id): JsonResponse
    {
        $item = $this->service->update($id, $request->validated());

        return $this->successResponse(payload: new CartItemResource($item), message: __('messages.updated'));
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($id);

        return $this->successResponse(message: __('messages.deleted'), code: 204);
    }
}
