<?php

namespace Modules\Basket\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Basket\Services\BasketService;

class BasketController
{
    public function __construct(
        private BasketService $basketService
    ) {}

    public function index(Request $request): JsonResponse
    {
        $sessionId = $request->session()->getId();
        return response()->json($this->basketService->getBasket($sessionId));
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'product_id' => 'required|integer',
            'product_name' => 'required|string|max:255',
            'price' => 'required|numeric',
            'unit' => 'nullable|string|max:100',
            'unit_price' => 'nullable|numeric',
            'image_url' => 'nullable|string',
            'quantity' => 'integer|min:1',
        ]);
        $data['session_id'] = $request->session()->getId();

        return response()->json($this->basketService->addItem($data), 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $data = $request->validate(['quantity' => 'required|integer|min:0']);

        if ($data['quantity'] === 0) {
            $this->basketService->removeItem($id);
            return response()->json(null, 204);
        }

        return response()->json($this->basketService->updateQuantity($id, $data['quantity']));
    }

    public function destroy(int $id): JsonResponse
    {
        $this->basketService->removeItem($id);
        return response()->json(null, 204);
    }

    public function clear(Request $request): JsonResponse
    {
        $sessionId = $request->session()->getId();
        $this->basketService->clearBasket($sessionId);
        return response()->json(null, 204);
    }
}
