<?php

namespace App\Service\ThirdParty;

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

class KoraService implements BVNVerificationInterface, NINVerificationInterface
{
    use JsonResponseTrait;

    protected $baseUrl;
    protected $apiKey;

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

    public function verifyBVN(string $bvn): object
    {
        try {
            $url = "{$this->baseUrl}/bvn/verify";
            $response = Http::withHeaders([
                'Authorization' => $this->apiKey,
            ])->post($url, [
                'bvn' => $bvn,
            ]);

            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): array
    {
        try {
            $url = "{$this->baseUrl}/nin/verify";
            $response = Http::withHeaders([
                'Authorization' => $this->apiKey,
            ])->post($url, ['nin' => $nin]);

            if ($response->failed()) {
                return $this->exceptionErrors(
                    data: $response->json(),
                    statusCode: $response->status(),
                    message: 'Failed to verify NIN with Kora.',
                );
            }

            return $response->json();
        } catch (\Exception $e) {
            \Log::error('KoraService verifyNIN error: ' . $e->getMessage());
            return $this->errorResponse(statusCode: 500, message: 'An error occurred.');
        }
    }
}
