<?php

namespace App\Http\Controllers;

use App\Services\Billing\BillingClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

/**
 * Lightweight wallet balance for the avatar dropdown widget.
 */
class WalletBalanceController extends Controller
{
    public function balance(Request $request, BillingClient $billing): JsonResponse
    {
        $publicId = (string) $request->user()->public_id;

        $minor = Cache::remember("wallet_balance:{$publicId}", now()->addSeconds(30), function () use ($billing, $publicId) {
            try {
                return $billing->balanceMinor($publicId);
            } catch (\Throwable) {
                return null;
            }
        });

        if ($minor === null) {
            return response()->json(['available' => false]);
        }

        $currency = (string) config('billing.currency', 'GHS');

        return response()->json([
            'available' => true,
            'balance_minor' => $minor,
            'currency' => $currency,
            'formatted' => $currency.' '.number_format($minor / 100, 2),
        ]);
    }
}
