<?php

namespace App\Http\Controllers;

use App\Contracts\NationalIdentityProvider;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use RuntimeException;
use Throwable;

class NinLookupController extends Controller
{
    public function __invoke(Request $request, NationalIdentityProvider $provider): JsonResponse
    {
        if (! $provider->isConfigured()) {
            return response()->json([
                'configured' => false,
                'found' => false,
                'message' => 'Live NIDA verification is disabled or no authorized provider endpoint is configured. Enter the NIN manually and continue.',
            ], 409);
        }

        $data = $request->validate([
            'nin' => ['required', 'string', 'regex:/^\d{20}$/'],
        ], [
            'nin.regex' => 'NIN must contain exactly 20 digits.',
        ]);

        try {
            $identity = $provider->lookup($data['nin']);
        } catch (RuntimeException $exception) {
            report($exception);

            return response()->json([
                'configured' => true,
                'found' => false,
                'message' => $exception->getMessage(),
            ], 502);
        } catch (Throwable $exception) {
            report($exception);

            return response()->json([
                'configured' => true,
                'found' => false,
                'message' => 'NIDA lookup failed unexpectedly. You can continue with manual customer entry.',
            ], 502);
        }

        return response()->json([
            'configured' => true,
            'found' => (bool) $identity,
            'data' => $identity,
            'message' => $identity ? 'Identity found and customer details loaded.' : 'No identity record was found for this NIN.',
        ]);
    }
}
