const express = require('express');
const router = express.Router();
const { Pool } = require('pg');
const { createClient } = require('redis');
const UAParser = require('ua-parser-js');

const pgPool = new Pool({
    host: process.env.PGHOST || 'postgres',
    port: process.env.PGPORT || 5432,
    user: process.env.PGUSER || 'postgres',
    password: process.env.PGPASSWORD || 'postgres',
    database: process.env.PGDATABASE || 'ckqr',
});

const redisClient = createClient({
    url: `redis://${process.env.REDIS_HOST || 'redis'}:${process.env.REDIS_PORT || 6379}`
});
redisClient.on('error', (err) => console.log('Redis Client Error', err));
(async () => {
    if (!redisClient.isOpen) await redisClient.connect();
})();

router.get('/:shortUrlId', async (req, res) => {
    const { shortUrlId } = req.params;
    const cacheKey = `qr:${shortUrlId}:full`;

    try {
        let qrData = null;

        // 1. Check Cache
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            qrData = JSON.parse(cachedData);
        } else {
            // 2. Not in cache, check DB
            const result = await pgPool.query(
                `SELECT q.id as qr_id, q.destination_url, q.data_type, q.routing_data, u.role 
                 FROM qr_codes q 
                 JOIN users u ON q.user_id = u.id 
                 WHERE q.short_url_id = $1`,
                [shortUrlId]
            );

            if (result.rows.length === 0) {
                return res.status(404).send('QR Code not found');
            }
            
            qrData = result.rows[0];
            await redisClient.setEx(cacheKey, 3600, JSON.stringify(qrData));
        }

        // 3. Track Analytics (Async so it doesn't block redirection)
        const parser = new UAParser(req.headers['user-agent']);
        const os = parser.getOS().name || 'Unknown';
        const deviceType = parser.getDevice().type || 'desktop';
        const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        const country = req.headers['cf-ipcountry'] || 'Unknown';

        pgPool.query(
            `INSERT INTO qr_scans (qr_code_id, ip_address, user_agent, os, device_type, country) 
             VALUES ($1, $2, $3, $4, $5, $6)`,
            [qrData.qr_id, ip, req.headers['user-agent'], os, deviceType, country]
        ).catch(err => console.error('Failed to log scan:', err));

        // 4. Determine final destination based on data_type
        let finalDestination = qrData.destination_url;
        let isDirectAction = false;
        let isDownload = false;
        let downloadContent = '';

        if (qrData.data_type === 'App Store' && qrData.routing_data) {
            const rd = typeof qrData.routing_data === 'string' ? JSON.parse(qrData.routing_data) : qrData.routing_data;
            if (os === 'iOS' || os === 'Mac OS') {
                finalDestination = rd.ios || rd.fallback;
            } else if (os === 'Android') {
                finalDestination = rd.android || rd.fallback;
            } else {
                finalDestination = rd.fallback || rd.ios || rd.android;
            }
        } else if (qrData.data_type === 'Email' && qrData.routing_data) {
            const rd = typeof qrData.routing_data === 'string' ? JSON.parse(qrData.routing_data) : qrData.routing_data;
            finalDestination = `mailto:${rd.email}?subject=${encodeURIComponent(rd.subject || '')}&body=${encodeURIComponent(rd.body || '')}`;
            isDirectAction = true;
        } else if (qrData.data_type === 'SMS' && qrData.routing_data) {
            const rd = typeof qrData.routing_data === 'string' ? JSON.parse(qrData.routing_data) : qrData.routing_data;
            finalDestination = `sms:${rd.phone}?body=${encodeURIComponent(rd.message || '')}`;
            isDirectAction = true;
        } else if (qrData.data_type === 'vCard' && qrData.routing_data) {
            const rd = typeof qrData.routing_data === 'string' ? JSON.parse(qrData.routing_data) : qrData.routing_data;
            isDownload = true;
            downloadContent = `BEGIN:VCARD\r\nVERSION:3.0\r\nN:${rd.lastName || ''};${rd.firstName || ''}\r\nFN:${rd.firstName || ''} ${rd.lastName || ''}\r\nORG:${rd.company || ''}\r\nTITLE:${rd.title || ''}\r\nTEL:${rd.phone || ''}\r\nEMAIL:${rd.email || ''}\r\nEND:VCARD`;
        } else if (qrData.data_type === 'Wi-Fi') {
            return res.send('Wi-Fi QR Codes are meant to be scanned natively as static QRs.');
        }

        if (isDownload) {
            res.setHeader('Content-Type', 'text/vcard');
            res.setHeader('Content-Disposition', 'attachment; filename="contact.vcf"');
            return res.send(downloadContent);
        }

        // 5. Check Tier & Redirect
        if (qrData.role === 'free' && !isDirectAction) {
            const encodedUrl = encodeURIComponent(finalDestination);
            // In production, this points to the real Next.js domain
            const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:4000';
            return res.redirect(302, `${frontendUrl}/ad-redirect?url=${encodedUrl}`);
        } else {
            // Paid users or Direct Actions (mailto/sms) skip the ad
            return res.redirect(302, finalDestination);
        }

    } catch (err) {
        console.error(err);
        res.status(500).send('Server Error during redirection');
    }
});

module.exports = router;
