<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class BalanceController extends Controller
{
    public function index(Request $request)
{
    $user = $request->user();

    if (!$user) {
        return response()->json([
            'success' => false,
            'message' => 'Unauthorized'
        ], 401);
    }

    // 🔥 log (buat tracking attacker)
    Log::warning('BALANCE HIT', [
        'user_id' => $user->id,
        'ip' => $request->ip(),
    ]);

    // 🔒 anti burst
    $lockKey = 'balance_lock_'.$user->id;

    if (Cache::has($lockKey)) {
        return response()->json([
            'success' => true,
            'data' => [
                'balance' => (int) $user->balance,
                'currency' => 'IDR'
            ]
        ]);
    }

    Cache::put($lockKey, true, 3);

    // ⚡ cache
    $balance = Cache::remember(
        'balance_'.$user->id,
        5,
        fn() => (int) $user->balance
    );

    return response()->json([
        'success' => true,
        'data' => [
            'balance' => $balance,
            'currency' => 'IDR'
        ]
    ]);
}
}