<?php

namespace App\Service\ThirdParty;

use App\Service\ThirdParty\Interfaces\BVNVerificationInterface;
use App\Service\ThirdParty\Interfaces\NINVerificationInterface;
use Illuminate\Support\Facades\Http;

class DojaService implements BVNVerificationInterface, NINVerificationInterface
{
    protected $baseUrl;
    protected $apiKey;
    protected $appId;

    public function __construct()
    {
        $this->baseUrl = config('thirdparty.dojah.base_url');
        $this->apiKey = config('thirdparty.dojah.secret_key');
        $this->appId = config('thirdparty.dojah.app_id');
    }

    public function verifyBVN(string $bvn):object
    {
        try{

            $url = "{$this->baseUrl}/kyc/bvn/full";
            $response = Http::withHeaders([
                'Authorization' => $this->apiKey,
                'AppId'=>$this->appId,

            ])->get($url, [
                'bvn' => $bvn,
            ]);

            // dd($response);
            if ($response->successful()) {
                return (object) $response->json(); // Cast the response to an object
            }

            // Handle failure response
            return (object) [
                'error' => $response->json('error') ?? 'Failed to verify BVN',
            ];
        } catch (\Exception $e) {
            // Log the exception for debugging
            \Log::error('DojaService verifyBVN error: ' . $e->getMessage());

            // Return an error response as an object
            return (object) [
                'error' => 'An error occurred while verifying BVN. Please try again later.',
            ];
        }
    }

    public function verifyNIN(string $nin): object
    {
        try {
            $url = "{$this->baseUrl}/kyc/nin/verify";
            $response = Http::withHeaders([
                'Authorization' => $this->apiKey,
                'AppId' => $this->appId,
            ])->get($url, ['nin' => $nin]);

            if ($response->successful()) {
                return (object) $response->json(); // Cast the response to an object
            }

            // Handle failure response
            return (object) [
                'error' => $response->json('error') ?? 'Failed to verify NIN',
            ];
        } catch (\Exception $e) {
            \Log::error('DojaService verifyNIN error: ' . $e->getMessage());
            // Return an error response as an object
            return (object) [
                'error' => 'An error occurred while verifying BVN. Please try again later.',
            ];
        }
    }
}
