<?php

namespace App\Services\Verification\Drivers;

use App\Services\Verification\Contracts\VerificationProviderInterface;
use App\Services\Verification\DTOs\AadhaarBasicResult;
use App\Services\Verification\DTOs\AadhaarOtpResult;
use App\Services\Verification\DTOs\AadhaarPanLinkResult;
use App\Services\Verification\DTOs\AadhaarVerificationResult;
use App\Services\Verification\DTOs\GstVerificationResult;
use App\Services\Verification\DTOs\PanVerificationResult;
use App\Services\Verification\DTOs\BankVerificationResult;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SurepassDriver implements VerificationProviderInterface
{
    protected string $apiKey;
    protected string $baseUrl;

    public function __construct(array $config)
    {
        $this->apiKey = $config['api_key'] ?? '';
        $this->baseUrl = $config['base_url'] ?? 'https://api.surepass.io/api/v1/';
    }

    protected function client()
    {
        return Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->apiKey,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])->baseUrl($this->baseUrl);
    }

    public function verifyPan(string $panNumber, ?string $fullName = null, ?string $dob = null): PanVerificationResult
    {
        try {
            $response = $this->client()->post('pan/pan', [
                'id_number' => strtoupper(trim($panNumber))
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                
                return new PanVerificationResult(
                    valid: true,
                    panNumber: $data['pan_number'] ?? $panNumber,
                    fullName: $data['full_name'] ?? null,
                    firstName: $data['first_name'] ?? null,
                    middleName: $data['middle_name'] ?? null,
                    lastName: $data['last_name'] ?? null,
                    category: $data['category'] ?? null,
                    isIndividual: ($data['category'] ?? '') === 'Individual',
                    rawData: $body
                );
            }

            return new PanVerificationResult(
                valid: false,
                panNumber: $panNumber,
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass PAN verification failed: ' . $e->getMessage());
            return new PanVerificationResult(
                valid: false,
                panNumber: $panNumber,
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function sendAadhaarOtp(string $aadhaarNumber): AadhaarOtpResult
    {
        try {
            $response = $this->client()->post('aadhaar-v2/generate-otp', [
                'id_number' => trim($aadhaarNumber)
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                return new AadhaarOtpResult(
                    otpSent: true,
                    clientId: $data['client_id'] ?? null,
                    message: $body['message'] ?? 'OTP sent successfully.',
                    rawData: $body
                );
            }

            return new AadhaarOtpResult(
                otpSent: false,
                message: $body['message'] ?? 'Failed to send OTP.',
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass Aadhaar OTP send failed: ' . $e->getMessage());
            return new AadhaarOtpResult(
                otpSent: false,
                message: 'Internal error while sending OTP: ' . $e->getMessage(),
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function verifyAadhaarOtp(string $otp, string $clientId): AadhaarVerificationResult
    {
        try {
            $response = $this->client()->post('aadhaar-v2/submit-otp', [
                'otp' => trim($otp),
                'client_id' => trim($clientId)
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                
                return new AadhaarVerificationResult(
                    valid: true,
                    aadhaarNumber: $data['aadhaar_number'] ?? '',
                    fullName: $data['full_name'] ?? null,
                    gender: $data['gender'] ?? null,
                    dob: $data['dob'] ?? null,
                    address: $data['address'] ?? null,
                    photoBase64: $data['profile_image'] ?? null,
                    rawData: $body
                );
            }

            return new AadhaarVerificationResult(
                valid: false,
                aadhaarNumber: '',
                rawData: $body ?? ['error' => 'API verification failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass Aadhaar OTP verification failed: ' . $e->getMessage());
            return new AadhaarVerificationResult(
                valid: false,
                aadhaarNumber: '',
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function verifyAadhaarBasic(string $aadhaarNumber): AadhaarBasicResult
    {
        try {
            $response = $this->client()->post('aadhaar/basic', [
                'id_number' => trim($aadhaarNumber)
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                return new AadhaarBasicResult(
                    valid: true,
                    aadhaarNumber: $aadhaarNumber,
                    ageBand: $data['age_band'] ?? null,
                    gender: $data['gender'] ?? null,
                    state: $data['state'] ?? null,
                    rawData: $body
                );
            }

            return new AadhaarBasicResult(
                valid: false,
                aadhaarNumber: $aadhaarNumber,
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass Aadhaar Basic verification failed: ' . $e->getMessage());
            return new AadhaarBasicResult(
                valid: false,
                aadhaarNumber: $aadhaarNumber,
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function checkAadhaarPanLink(string $aadhaarNumber, string $panNumber): AadhaarPanLinkResult
    {
        try {
            $response = $this->client()->post('pan/pan-aadhaar-link', [
                'pan' => strtoupper(trim($panNumber)),
                'aadhaar' => trim($aadhaarNumber)
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                return new AadhaarPanLinkResult(
                    linked: $data['is_linked'] ?? false,
                    panNumber: strtoupper($panNumber),
                    aadhaarNumber: $aadhaarNumber,
                    message: $body['message'] ?? 'Checked linkage status successfully.',
                    rawData: $body
                );
            }

            return new AadhaarPanLinkResult(
                linked: false,
                panNumber: $panNumber,
                aadhaarNumber: $aadhaarNumber,
                message: $body['message'] ?? 'Failed to check link status.',
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass Aadhaar PAN link check failed: ' . $e->getMessage());
            return new AadhaarPanLinkResult(
                linked: false,
                panNumber: $panNumber,
                aadhaarNumber: $aadhaarNumber,
                message: 'Error during link check execution: ' . $e->getMessage(),
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function verifyGst(string $gstin): GstVerificationResult
    {
        try {
            $response = $this->client()->post('gst/search', [
                'gstin' => strtoupper(trim($gstin))
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                
                return new GstVerificationResult(
                    valid: true,
                    gstin: $data['gstin'] ?? $gstin,
                    legalName: $data['lgnm'] ?? null,
                    tradeName: $data['trade_name'] ?? null,
                    status: $data['sts'] ?? null,
                    registrationDate: $data['rgdt'] ?? null,
                    taxpayerType: $data['dty'] ?? null,
                    address: $data['pradr'] ?? null,
                    rawData: $body
                );
            }

            return new GstVerificationResult(
                valid: false,
                gstin: $gstin,
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass GST verification failed: ' . $e->getMessage());
            return new GstVerificationResult(
                valid: false,
                gstin: $gstin,
                rawData: ['error' => $e->getMessage()]
            );
        }
    }

    public function verifyBank(string $accountNumber, string $ifsc): BankVerificationResult
    {
        try {
            $response = $this->client()->post('bank/penny-drop', [
                'account_number' => trim($accountNumber),
                'ifsc' => strtoupper(trim($ifsc))
            ]);

            $body = $response->json();

            if ($response->successful() && isset($body['success']) && $body['success']) {
                $data = $body['data'] ?? [];
                
                return new BankVerificationResult(
                    valid: true,
                    accountNumber: $data['account_number'] ?? $accountNumber,
                    ifsc: $data['ifsc'] ?? $ifsc,
                    accountName: $data['full_name'] ?? $data['account_holder_name'] ?? null,
                    bankName: $data['bank_name'] ?? null,
                    rawData: $body
                );
            }

            return new BankVerificationResult(
                valid: false,
                accountNumber: $accountNumber,
                ifsc: $ifsc,
                rawData: $body ?? ['error' => 'API response failed']
            );
        } catch (\Exception $e) {
            Log::error('Surepass bank verification failed: ' . $e->getMessage());
            return new BankVerificationResult(
                valid: false,
                accountNumber: $accountNumber,
                ifsc: $ifsc,
                rawData: ['error' => $e->getMessage()]
            );
        }
    }
}
