<?php

namespace App\Http\Controllers\Api\v1;

use App\Services\Verification\Contracts\VerificationProviderInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GstVerificationController extends BaseVerificationController
{
    public function __construct(
        protected VerificationProviderInterface $provider
    ) {}

    /**
     * Verify a GSTIN (GST registration number).
     */
    public function verify(Request $request): JsonResponse
    {
        $insufficientBalance = $this->hasInsufficientBalance($request, 'gst_charge', $charge);
        if ($insufficientBalance) {
            return $insufficientBalance;
        }

        $validated = $request->validate([
            'gstin' => ['required', 'string', 'regex:/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/i']
        ]);

        $gstin = strtoupper(trim($validated['gstin']));
        $startTime = microtime(true);

        $result = $this->provider->verifyGst($gstin);

        $endTime = microtime(true);
        $durationMs = (int) (($endTime - $startTime) * 1000);

        // Charge the wallet
        $this->chargeWallet($request, $charge);

        $status = $result->valid ? 'success' : 'failed';
        $errorMessage = $result->valid ? null : ($result->rawData['message'] ?? 'GST verification failed');

        $this->logVerification(
            request: $request,
            type: 'gst',
            inputParams: ['gstin' => $gstin],
            status: $status,
            provider: $this->provider->getDefaultDriver(),
            responseTimeMs: $durationMs,
            errorMessage: $errorMessage,
            chargedAmount: $charge
        );

        return response()->json([
            'success' => $result->valid,
            'data' => [
                'valid' => $result->valid,
                'gstin' => $result->gstin,
                'legal_name' => $result->legalName,
                'trade_name' => $result->tradeName,
                'status' => $result->status,
                'registration_date' => $result->registrationDate,
                'taxpayer_type' => $result->taxpayerType,
                'address' => $result->address,
            ]
        ], $result->valid ? 200 : 400);
    }
}
