<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Http\Requests\VerifyBvnRequest;
use App\Services\BvnVerificationApiService;
use App\Services\NinEncryptionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class BvnVerificationController extends Controller
{
    public function __construct(
        private readonly NinEncryptionService $ninEncryptionService,
        private readonly BvnVerificationApiService $bvnVerificationApiService,
    ) {}

    /**
     * Verify a BVN and return the identity data from the external API.
     * Decrypts the RSA-OAEP encrypted BVN sent from the frontend,
     * calls Dojah, and returns whatever Dojah returns. Nothing is stored.
     */
    public function verify(VerifyBvnRequest $request): JsonResponse
    {
        // Step 1: RSA-OAEP decrypt the BVN
        try {
            $decryptedBvn = $this->ninEncryptionService->decryptWithPrivateKey($request->validated('encrypted_bvn'));
        } catch (\Exception $e) {
            Log::warning('BVN verify: RSA decryption failed', ['error' => $e->getMessage()]);
            return response()->json([
                'success' => false,
                'message' => 'Invalid encrypted data.',
            ], 422);
        }

        // Step 2: Validate BVN format (11 digits)
        if (! $this->ninEncryptionService->validateNinFormat($decryptedBvn)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid BVN format. BVN must be 11 digits.',
            ], 422);
        }

        // Step 3: Call Dojah and return the result
        $result = $this->bvnVerificationApiService->verifyBvn($decryptedBvn);

        if (! $result['success'] || ! $result['verified']) {
            $serviceDown = $result['service_unavailable'] ?? false;
            $status = $serviceDown ? 503 : 422;
            return response()->json(array_filter([
                'success'      => false,
                'service_down' => $serviceDown ?: null,
                'message'      => $result['message'] ?? 'BVN verification failed.',
            ]), $status);
        }

        return response()->json([
            'success' => true,
            'message' => 'BVN verified successfully.',
            'data'    => $result['data'],
        ]);
    }
}
