<?php

namespace App\Http\Controllers\Api\v1;

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

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

    /**
     * Generate and send OTP for Aadhaar verification.
     */
    public function sendOtp(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'aadhaar_otp_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'aadhaar_number' => ['required', 'string', 'regex:/^[0-9]{12}$/']
        ]);

        $aadhaar = trim($validated['aadhaar_number']);
        $startTime = microtime(true);

        $result = $this->provider->sendAadhaarOtp($aadhaar);

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

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

        $status = $result->otpSent ? 'success' : 'failed';
        $errorMessage = $result->otpSent ? null : $result->message;

        $this->logVerification(
            request: $request,
            type: 'aadhaar_otp_send',
            inputParams: ['aadhaar_number' => $aadhaar],
            status: $status,
            provider: $this->provider->getDefaultDriver(),
            responseTimeMs: $durationMs,
            errorMessage: $errorMessage,
            chargedAmount: $charge
        );

        return response()->json([
            'success' => $result->otpSent,
            'message' => $result->message,
            'data' => [
                'otp_sent' => $result->otpSent,
                'client_id' => $result->clientId,
            ]
        ], $result->otpSent ? 200 : 400);
    }

    /**
     * Submit OTP to complete Aadhaar verification (eKYC).
     */
    public function submitOtp(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'aadhaar_submit_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'otp' => ['required', 'string', 'regex:/^[0-9]{6}$/'],
            'client_id' => ['required', 'string']
        ]);

        $otp = trim($validated['otp']);
        $clientId = trim($validated['client_id']);
        $startTime = microtime(true);

        $result = $this->provider->verifyAadhaarOtp($otp, $clientId);

        $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'] ?? 'Aadhaar OTP verification failed');

        $this->logVerification(
            request: $request,
            type: 'aadhaar_otp_submit',
            inputParams: ['client_id' => $clientId, 'otp' => $otp],
            status: $status,
            provider: $this->provider->getDefaultDriver(),
            responseTimeMs: $durationMs,
            errorMessage: $errorMessage,
            chargedAmount: $charge,
            responseData: $result->valid ? [
                'full_name' => $result->fullName,
                'gender' => $result->gender,
                'dob' => $result->dob,
                'address' => $result->address,
                'photo_base64' => $result->photoBase64,
            ] : null
        );

        return response()->json([
            'success' => $result->valid,
            'data' => [
                'valid' => $result->valid,
                'aadhaar_number' => $result->aadhaarNumber,
                'full_name' => $result->fullName,
                'gender' => $result->gender,
                'dob' => $result->dob,
                'address' => $result->address,
                'photo_base64' => $result->photoBase64,
            ]
        ], $result->valid ? 200 : 400);
    }

    /**
     * Basic Aadhaar lookup (without OTP).
     */
    public function basicVerify(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'aadhaar_basic_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'aadhaar_number' => ['required', 'string', 'regex:/^[0-9]{12}$/']
        ]);

        $aadhaar = trim($validated['aadhaar_number']);
        $startTime = microtime(true);

        $result = $this->provider->verifyAadhaarBasic($aadhaar);

        $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'] ?? 'Aadhaar basic verification failed');

        $this->logVerification(
            request: $request,
            type: 'aadhaar_basic',
            inputParams: ['aadhaar_number' => $aadhaar],
            status: $status,
            provider: $this->provider->getDefaultDriver(),
            responseTimeMs: $durationMs,
            errorMessage: $errorMessage,
            chargedAmount: $charge
        );

        return response()->json([
            'success' => $result->valid,
            'data' => [
                'valid' => $result->valid,
                'aadhaar_number' => $result->aadhaarNumber,
                'age_band' => $result->ageBand,
                'gender' => $result->gender,
                'state' => $result->state,
            ]
        ], $result->valid ? 200 : 400);
    }
}
