<?php

namespace Modules\Cart\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Cart\Services\CartService;

class CartController
{
    public function __construct(
        private CartService $cartService
    ) {}

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

    public function summary(Request $request): JsonResponse
    {
        $sessionId = $request->session()->getId();
        return response()->json($this->cartService->getCartTotal($sessionId));
    }

    protected function getNumericProductId($productId): int
    {
        if (is_numeric($productId)) {
            return (int) $productId;
        }
        
        try {
            $product = \Modules\Product\Models\Product::where('slug', $productId)->first();
            if ($product) {
                return $product->id;
            }
        } catch (\Throwable $e) {
        }
        
        return 1;
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'product_id' => 'required',
            '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['product_id'] = $this->getNumericProductId($data['product_id']);
        $data['session_id'] = $request->session()->getId();
        return response()->json($this->cartService->addItem($data), 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $data = $request->validate(['quantity' => 'required|integer|min:1']);
        return response()->json($this->cartService->updateQuantity($id, $data['quantity']));
    }

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

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

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

        $items = [];
        foreach ($data['items'] as $item) {
            $item['product_id'] = $this->getNumericProductId($item['product_id']);
            $item['session_id'] = $sessionId;
            $items[] = $item;
        }

        return response()->json($this->cartService->syncCart($sessionId, $items));
    }
}
