<?php

namespace App\Http\Controllers\Api\v1;

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

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

    /**
     * Verify a PAN card number.
     */
    public function verify(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'pan_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'pan_number' => ['required', 'string', 'regex:/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i'],
            'name_as_per_pan' => ['nullable', 'string'],
            'date_of_birth' => ['nullable', 'string']
        ]);

        $pan = strtoupper(trim($validated['pan_number']));
        $nameAsPerPan = $validated['name_as_per_pan'] ?? null;
        $dob = $validated['date_of_birth'] ?? null;
        $startTime = microtime(true);

        $result = $this->provider->verifyPan($pan, $nameAsPerPan, $dob);

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

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

        return response()->json([
            'success' => $result->valid,
            'data' => [
                'valid' => $result->valid,
                'pan_number' => $result->panNumber,
                'full_name' => $result->fullName,
                'first_name' => $result->firstName,
                'middle_name' => $result->middleName,
                'last_name' => $result->lastName,
                'category' => $result->category,
                'is_individual' => $result->isIndividual,
            ]
        ], $result->valid ? 200 : 400);
    }
}
