<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\ProductVariant;
use App\Services\CartService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

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

    public function index()
    {
        $cart = $this->cartService->currentCart(false);

        return view('cart.index', compact('cart'));
    }

    public function add(Request $request, Product $product): RedirectResponse
    {
        $validated = $request->validate([
            'quantity' => ['nullable', 'integer', 'min:1'],
            'product_variant_id' => ['nullable', 'integer'],
        ]);

        if (! $product->is_active) {
            return back()->with('error', 'This product is currently unavailable.');
        }

        $quantity = (int) ($validated['quantity'] ?? 1);
        $variant = null;

        if ($product->has_variants) {
            $variant = ProductVariant::where('product_id', $product->id)
                ->where('id', $validated['product_variant_id'] ?? null)
                ->first();

            if (! $variant) {
                return back()->with('error', 'Please select an available size and colour combination.');
            }

            if (! $variant->is_active || ! $variant->isInStock()) {
                return back()->with('error', 'The selected option is currently out of stock.');
            }
        } else {
            if (! $product->isInStock()) {
                return back()->with('error', 'This product is currently unavailable.');
            }
        }

        try {
            $this->cartService->addProduct($product, $quantity, $variant);
        } catch (\RuntimeException $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Added to cart.');
    }

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

        $this->cartService->updateQuantity($itemId, $request->integer('quantity'));

        return back()->with('success', 'Cart updated.');
    }

    public function remove(int $itemId): RedirectResponse
    {
        $this->cartService->removeItem($itemId);

        return back()->with('success', 'Item removed from cart.');
    }
}
