<?php

namespace App\Http\Controllers\Api\v1;

use App\Services\Verification\Contracts\VerificationProviderInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BankVerificationController extends BaseVerificationController
{
    public function __construct(
        protected VerificationProviderInterface $provider
    ) {}

    /**
     * Verify a bank account number and IFSC code.
     */
    public function verify(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'bank_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'account_number' => ['required', 'string', 'regex:/^[0-9]{9,18}$/'],
            'ifsc' => ['required', 'string', 'regex:/^[A-Z]{4}0[A-Z0-9]{6}$/i']
        ]);

        $accountNumber = trim($validated['account_number']);
        $ifsc = strtoupper(trim($validated['ifsc']));
        $startTime = microtime(true);

        $result = $this->provider->verifyBank($accountNumber, $ifsc);

        $endTime = microtime(true);
        $durationMs = (int) (($endTime - $startTime) * 1000);

        // Charge the wallet
        $this->chargeWallet($request, $charge);

        $status = $result->valid ? 'success' : 'failed';
        $errorMessage = $result->valid ? null : ($result->rawData['message'] ?? 'Bank account verification failed');

        $this->logVerification(
            request: $request,
            type: 'bank',
            inputParams: ['account_number' => $accountNumber, 'ifsc' => $ifsc],
            status: $status,
            provider: $this->provider->getDefaultDriver(),
            responseTimeMs: $durationMs,
            errorMessage: $errorMessage,
            chargedAmount: $charge
        );

        return response()->json([
            'success' => $result->valid,
            'data' => [
                'valid' => $result->valid,
                'account_number' => $result->accountNumber,
                'ifsc' => $result->ifsc,
                'account_name' => $result->accountName,
                'bank_name' => $result->bankName,
            ]
        ], $result->valid ? 200 : 400);
    }
}
