<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Wallet;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Checkout\Session as StripeSession;

class WalletController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $wallet = $request->user()->wallet ?? Wallet::create(['user_id' => $request->user()->id]);
        return response()->json($wallet);
    }

    public function transactions(Request $request): JsonResponse
    {
        $txns = $request->user()
            ->walletTransactions()
            ->latest()
            ->paginate(20);

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

    public function topup(Request $request): JsonResponse
    {
        $data = $request->validate([
            'amount' => 'required|integer|min:100|max:100000', // ₹100 – ₹1,00,000
        ]);

        $user = $request->user();

        Stripe::setApiKey(config('services.stripe.secret'));

        $session = StripeSession::create([
            'payment_method_types' => ['card'],
            'mode'                 => 'payment',
            'customer_email'       => $user->email,
            'line_items'           => [[
                'price_data' => [
                    'currency'     => 'inr',
                    'unit_amount'  => $data['amount'] * 100, // paise
                    'product_data' => [
                        'name' => 'Swagvio Wallet Top-Up',
                    ],
                ],
                'quantity' => 1,
            ]],
            'metadata' => [
                'user_id' => $user->id,
                'amount'  => $data['amount'],
            ],
            'success_url' => config('app.frontend_url') . '/escort/wallet.html?topup=success&session_id={CHECKOUT_SESSION_ID}',
            'cancel_url'  => config('app.frontend_url') . '/escort/wallet.html?topup=cancelled',
        ]);

        return response()->json([
            'checkout_url' => $session->url,
            'session_id'   => $session->id,
        ]);
    }

    /**
     * Called by frontend after Stripe redirect (secondary check; primary credit via webhook).
     */
    public function confirmTopup(Request $request): JsonResponse
    {
        $data = $request->validate(['session_id' => 'required|string']);

        Stripe::setApiKey(config('services.stripe.secret'));

        $session = StripeSession::retrieve($data['session_id']);

        if ($session->payment_status !== 'paid') {
            return response()->json(['message' => 'Payment not completed.'], 402);
        }

        // Idempotency: check if already credited via webhook
        $alreadyCredited = $request->user()
            ->walletTransactions()
            ->where('stripe_payment_id', $session->payment_intent)
            ->exists();

        if ($alreadyCredited) {
            return response()->json(['message' => 'Already credited.']);
        }

        // Credit wallet
        $wallet = $request->user()->wallet;
        $amount = (int) $session->metadata->amount;
        $wallet->credit($amount, 'Wallet top-up via Stripe', 'topup', $session->payment_intent);

        return response()->json([
            'message'     => "₹{$amount} added to your wallet.",
            'new_balance' => $wallet->fresh()->balance,
        ]);
    }
}
