/**
 * GST Verification Route
 * Verifies GSTIN and returns company details
 */

const express = require('express');
const router = express.Router();
const { authenticateApiKey } = require('../middleware/auth');
const { rateLimit } = require('../middleware/rateLimit');
const { verifyGSTIN } = require('../services/gstService');
const { logApiCall } = require('../services/analytics');

router.use(authenticateApiKey);
router.use(rateLimit);

router.get('/verify/:gstin', async (req, res, next) => {
    const startTime = Date.now();
    let success = false;

    try {
        const { gstin } = req.params;
        const gstinRegex = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}[A-Z][0-9A-Z]{1}$/;

        if (!gstinRegex.test(gstin.toUpperCase())) {
            return res.status(400).json({
                success: false,
                error: { code: 'INVALID_GSTIN', message: 'Invalid GSTIN format' }
            });
        }

        const result = await verifyGSTIN(gstin.toUpperCase());

        if (!result.success) {
            return res.status(result.statusCode || 404).json({
                success: false,
                error: { code: result.errorCode, message: result.message }
            });
        }

        success = true;

        res.json({
            success: true,
            data: result.data,
            meta: {
                request_id: `req_gst_${Date.now()}`,
                credits_used: 1,
                credits_remaining: req.user.remaining - 1,
                source: 'gstn'
            }
        });

    } catch (error) {
        next(error);
    } finally {
        await logApiCall({
            userId: req.user.id,
            apiKeyId: req.user.apiKeyId,
            endpoint: '/v1/gst/verify',
            method: 'GET',
            params: { gstin: req.params.gstin },
            status: success ? 200 : 500,
            duration: Date.now() - startTime,
            success,
            isTestKey: req.user.isTestKey
        });
    }
});

module.exports = router;
