<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\CartService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

    public function index(Request $request): JsonResponse
    {
        return response()->json($this->cartService->get($request));
    }

    public function add(Request $request): JsonResponse
    {
        $request->validate([
            'product_id' => 'required|integer|exists:products,id',
            'variant_id' => 'nullable|integer|exists:product_variants,id',
            'quantity' => 'required|integer|min:1|max:99',
        ]);

        $cart = $this->cartService->add(
            $request,
            $request->product_id,
            $request->variant_id,
            $request->quantity
        );

        return response()->json($cart);
    }

    public function update(Request $request): JsonResponse
    {
        $request->validate([
            'product_id' => 'required|integer',
            'variant_id' => 'nullable|integer',
            'quantity' => 'required|integer|min:0|max:99',
        ]);

        $cart = $this->cartService->update(
            $request,
            $request->product_id,
            $request->variant_id,
            $request->quantity
        );

        return response()->json($cart);
    }

    public function remove(Request $request): JsonResponse
    {
        $request->validate([
            'product_id' => 'required|integer',
            'variant_id' => 'nullable|integer',
        ]);

        $cart = $this->cartService->remove(
            $request,
            $request->product_id,
            $request->variant_id
        );

        return response()->json($cart);
    }

    public function applyDiscount(Request $request): JsonResponse
    {
        $request->validate([
            'code'     => 'required|string',
            'subtotal' => 'nullable|numeric|min:0',
        ]);

        try {
            $result = $this->cartService->applyDiscount($request, $request->code, (float) ($request->subtotal ?? 0));
            return response()->json($result);
        } catch (\InvalidArgumentException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function removeDiscount(Request $request): JsonResponse
    {
        return response()->json($this->cartService->removeDiscount($request));
    }
}
