<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class CacVerificationApiService
{
    private string $baseUrl;
    private ?string $appId;
    private ?string $secret;
    private int $timeout;

    public function __construct()
    {
        $env = config('nin.dojah_env', 'sandbox');

        $this->baseUrl = $env === 'live'
            ? 'https://api.dojah.io'
            : 'https://sandbox.dojah.io';

        $this->appId   = config('nin.dojah_app_id');
        $this->secret  = config('nin.dojah_secret');
        $this->timeout = config('nin.timeout', 30);
    }

    /**
     * Verify a company against the CAC Basic API.
     *
     * Dojah docs: https://docs.dojah.io/kyc/cac-lookup
     * Endpoint: GET /api/v1/kyc/cac/basic
     * Headers:  AppId, Authorization (raw secret — not Bearer)
     * Sandbox test RC numbers: 1261103, 14320749
     *
     * @param string $rcNumber    The CAC registration number
     * @param string $companyType One of: COMPANY, BUSINESS_NAME, INCORPORATED_TRUSTEES,
     *                            LIMITED_PARTNERSHIP, LIMITED_LIABILITY_PARTNERSHIP
     * @return array ['success', 'message', 'service_unavailable'?, 'data'?]
     */
    public function verifyCompany(string $rcNumber, string $companyType): array
    {
        $reference    = 'CAC_' . now()->format('ymdHis') . '_' . strtoupper(Str::random(6));
        $requestStart = microtime(true);

        try {
            Log::info('CAC verification request initiated', [
                'reference'    => $reference,
                'rc_number'    => $rcNumber,
                'company_type' => $companyType,
                'environment'  => config('nin.dojah_env'),
            ]);

            $response = Http::withHeaders([
                'AppId'         => $this->appId,
                'Authorization' => $this->secret,
                'Accept'        => 'application/json',
            ])
            ->timeout($this->timeout)
            ->get($this->baseUrl . '/api/v1/kyc/cac/basic', [
                'rc_number'    => $rcNumber,
                'company_type' => $companyType,
            ]);

            $duration = round((microtime(true) - $requestStart) * 1000, 2);

            Log::info('CAC verification response received', [
                'reference'   => $reference,
                'duration_ms' => $duration,
                'status_code' => $response->status(),
            ]);

            if ($response->successful()) {
                $entity = $response->json('entity');

                if (empty($entity)) {
                    return [
                        'success' => false,
                        'message' => 'Company not found. Please check the RC number and company type.',
                    ];
                }

                return [
                    'success' => true,
                    'message' => 'Company verified successfully.',
                    'data'    => [
                        'company_name'    => $entity['company_name'] ?? null,
                        'type_of_company' => $entity['type_of_company'] ?? null,
                        'rc_number'       => $entity['rc_number'] ?? null,
                        'business_number' => $entity['business_number'] ?? null,
                        'status'          => $entity['status'] ?? null,
                        'email'           => $entity['email'] ?? null,
                        'address'         => $entity['address'] ?? null,
                        'state'           => $entity['state'] ?? null,
                        'city'            => $entity['city'] ?? null,
                        'lga'             => $entity['lga'] ?? null,
                    ],
                ];
            }

            $duration = round((microtime(true) - $requestStart) * 1000, 2);

            $serviceUnavailable = in_array($response->status(), [401, 402, 403, 424, 429, 503]);
            $errorMessage       = $this->resolveErrorMessage($response->status(), $response->json());

            Log::error('CAC verification API error', [
                'reference'   => $reference,
                'duration_ms' => $duration,
                'status_code' => $response->status(),
                'error'       => $errorMessage,
            ]);

            return [
                'success'             => false,
                'service_unavailable' => $serviceUnavailable,
                'message'             => $errorMessage,
            ];

        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            $duration = round((microtime(true) - $requestStart) * 1000, 2);

            Log::error('CAC verification connection error', [
                'reference'   => $reference,
                'duration_ms' => $duration,
                'error'       => $e->getMessage(),
            ]);

            return [
                'success'             => false,
                'service_unavailable' => true,
                'message'             => 'CAC verification service is currently unavailable. Please try again later.',
            ];

        } catch (\Exception $e) {
            $duration = round((microtime(true) - $requestStart) * 1000, 2);

            Log::error('CAC verification unexpected error', [
                'reference'   => $reference,
                'duration_ms' => $duration,
                'error'       => $e->getMessage(),
            ]);

            return [
                'success'             => false,
                'service_unavailable' => true,
                'message'             => 'CAC verification service is currently unavailable. Please try again later.',
            ];
        }
    }

    private function resolveErrorMessage(int $status, ?array $body): string
    {
        return match ($status) {
            400 => 'Company not found. Please check the RC number and company type.',
            401 => 'CAC verification service authentication failed. Check your API credentials.',
            402 => 'CAC verification service wallet balance is insufficient.',
            403 => 'Access denied. Your plan does not include CAC verification.',
            424 => 'CAC verification upstream service is unavailable. Please try again later.',
            429 => 'CAC verification rate limit exceeded. Please try again shortly.',
            default => $body['error'] ?? $body['message'] ?? 'CAC verification failed.',
        };
    }
}
