<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Controller;
use App\Models\VerificationLog;
use Illuminate\Http\Request;

class BaseVerificationController extends Controller
{
    /**
     * Log the verification request in the database.
     */
    protected function logVerification(
        Request $request,
        string $type,
        array $inputParams,
        string $status,
        string $provider,
        int $responseTimeMs,
        ?string $errorMessage = null,
        float $chargedAmount = 0.00,
        ?array $responseData = null
    ): void {
        $client = $request->attributes->get('api_client');
        $clientId = $client ? $client->id : null;
        $companyName = $client ? $client->name : null;

        // Store full document numbers without masking
        $log = VerificationLog::create([
            'api_client_id' => $clientId,
            'verification_type' => $type,
            'input_parameters' => $inputParams,
            'status' => $status,
            'provider' => $provider,
            'response_time_ms' => $responseTimeMs,
            'error_message' => $errorMessage,
            'company_name' => $companyName,
            'charged_amount' => $chargedAmount,
        ]);

        // Also write to a per-type table for detailed per-document records.
        // Map common type prefixes to models.
        $typeModelMap = [
            'aadhaar' => \App\Models\AadhaarVerification::class,
            'aadhaar_pan_link' => \App\Models\AadhaarPanLinkVerification::class,
            'pan' => \App\Models\PanVerification::class,
            'gst' => \App\Models\GstVerification::class,
            'bank' => \App\Models\BankVerification::class,
        ];

        foreach ($typeModelMap as $prefix => $modelClass) {
            if (str_starts_with($type, $prefix)) {
                try {
                    $data = [
                        'verification_log_id' => $log->id,
                        'api_client_id' => $clientId,
                        'input_parameters' => $inputParams,
                        'status' => $status,
                        'provider' => $provider,
                        'response_time_ms' => $responseTimeMs,
                        'error_message' => $errorMessage,
                    ];

                    if ($prefix === 'aadhaar' && $responseData) {
                        $data['full_name'] = $responseData['full_name'] ?? null;
                        $data['gender'] = $responseData['gender'] ?? null;
                        $data['dob'] = $responseData['dob'] ?? null;
                        $data['address'] = $responseData['address'] ?? null;
                        $data['photo_base64'] = $responseData['photo_base64'] ?? null;
                    }

                    $modelClass::create($data);
                } catch (\Throwable $e) {
                    // Fail silently; logging can be added here if needed.
                }

                break;
            }
        }
    }

    /**
     * Check if client has enough balance and return the fee amount.
     */
    protected function hasInsufficientBalance(Request $request, string $chargeField, ?float &$chargeOut = null): ?\Illuminate\Http\JsonResponse
    {
        $client = $request->attributes->get('api_client');
        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'API Client not authenticated.',
            ], 401);
        }

        $chargeOut = (float) ($client->$chargeField ?? 0.00);

        if ($client->wallet_balance < $chargeOut) {
            return response()->json([
                'success' => false,
                'message' => 'Insufficient wallet balance. Please recharge.',
            ], 402);
        }

        return null;
    }

    /**
     * Debit the wallet balance of the client.
     */
    protected function chargeWallet(Request $request, float $amount): void
    {
        $client = $request->attributes->get('api_client');
        if ($client && $amount > 0) {
            $client->decrement('wallet_balance', $amount);
        }
    }
}
