<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WalletTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class WalletController extends Controller
{
    /**
     * GET /api/user/wallet — returns balance + paginated transactions.
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $perPage = min((int) $request->query('per_page', 20), 100);

        $txs = WalletTransaction::where('user_id', $user->id)
            ->orderByDesc('created_at')
            ->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => [
                'balance' => (float) $user->wallet_balance,
                'transactions' => $txs->items(),
                'pagination' => [
                    'current_page' => $txs->currentPage(),
                    'last_page' => $txs->lastPage(),
                    'total' => $txs->total(),
                ],
            ],
        ]);
    }

    /**
     * POST /api/user/wallet/deposit
     * Body: amount (positive integer, تومان)
     * Returns a payment intent — actual gateway flow is initiated by the
     * payment service. For now we record the transaction as pending until
     * verified. In production, link this to a real gateway authority.
     */
    public function deposit(Request $request)
    {
        $data = $request->validate([
            'amount' => ['required','integer','min:10000'],
            'gateway' => ['nullable','string','in:zarinpal,nextpay,bitpay,bazaar,myket'],
        ]);

        $user = Auth::user();
        $intentId = 'WALDEP-' . strtoupper(bin2hex(random_bytes(4)));

        return response()->json([
            'success' => true,
            'data' => [
                'intent_id' => $intentId,
                'amount' => $data['amount'],
                'gateway' => $data['gateway'] ?? 'zarinpal',
                'redirect_url' => null,
                'message' => 'برای تکمیل پرداخت به درگاه هدایت شوید',
            ],
        ]);
    }

    /**
     * POST /api/user/wallet/spend  (internal, used by checkout)
     * Reduces balance and writes a 'purchase' transaction. Wrapped in a DB
     * transaction so balance never drifts.
     */
    public function spend(Request $request)
    {
        $data = $request->validate([
            'amount' => ['required','integer','min:1'],
            'reference_type' => ['nullable','string'],
            'reference_id' => ['nullable','integer'],
        ]);

        $user = Auth::user();

        if ($user->wallet_balance < $data['amount']) {
            return response()->json([
                'success' => false,
                'message' => 'موجودی کیف پول کافی نیست',
            ], 422);
        }

        DB::transaction(function () use ($user, $data) {
            $before = $user->wallet_balance;
            $after = $before - $data['amount'];

            WalletTransaction::create([
                'user_id' => $user->id,
                'type' => 'purchase',
                'amount' => -1 * $data['amount'],
                'balance_before' => $before,
                'balance_after' => $after,
                'reference_id' => $data['reference_id'] ?? null,
                'reference_type' => $data['reference_type'] ?? null,
            ]);

            $user->update(['wallet_balance' => $after]);
        });

        return response()->json([
            'success' => true,
            'data' => ['balance' => (float) Auth::user()->fresh()->wallet_balance],
        ]);
    }
}
