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, 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.ip || req.connection.remoteAddress;

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

        // 4. Check Tier & Redirect
        if (qrData.role === 'free') {
            const encodedUrl = encodeURIComponent(qrData.destination_url);
            // 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 skip the ad
            return res.redirect(302, qrData.destination_url);
        }

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

module.exports = router;
