<?php

namespace App\Http\Controllers\Player;

use App\Http\Controllers\Controller;
use App\Models\RouletteItem;
use App\Services\RouletteService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use RuntimeException;

class RouletteController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Player/Roulette', [
            'items' => RouletteItem::query()->with('category:id,name')->get(),
            'donateBalance' => auth()->user()->donate_balance,
        ]);
    }

    public function spin(Request $request, RouletteService $roulette): RedirectResponse
    {
        $throttleKey = 'roulette-spin:'.$request->user()->id;

        // Rate limited independently of the balance-lock transaction —
        // stops a scripted burst of spins even before it reaches the DB.
        if (RateLimiter::tooManyAttempts($throttleKey, 10)) {
            throw ValidationException::withMessages([
                'spin' => 'You are spinning too quickly. Please wait a moment.',
            ]);
        }
        RateLimiter::hit($throttleKey, 10);

        try {
            $drop = $roulette->spin($request->user());
        } catch (RuntimeException $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', "You won: {$drop->item->name} (+{$drop->value})");
    }
}
