const jwt = require('jsonwebtoken');
const { Pool } = require('pg');

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 verifyToken = (req, res, next) => {
  let token = req.headers['authorization'];

  // Check cookies if no auth header
  if (!token && req.cookies && req.cookies.token) {
    token = req.cookies.token;
  } else if (token && token.startsWith('Bearer ')) {
    token = token.slice(7, token.length).trimLeft();
  }

  if (!token) return res.status(403).json({ error: 'Token missing from header' });

  jwt.verify(token, process.env.JWT_SECRET || 'supersecret123', (err, decoded) => {
    if (err) return res.status(401).json({ error: 'Unauthorized' });
    req.user = decoded;
    next();
  });
};

const requireEmailVerification = async (req, res, next) => {
    try {
        const userCheck = await pgPool.query('SELECT is_email_verified, created_at FROM users WHERE id = $1', [req.user.id]);
        if (userCheck.rows.length === 0) return res.status(403).json({ error: 'User not found' });
        
        const user = userCheck.rows[0];
        if (!user.is_email_verified) {
            const createdAt = new Date(user.created_at);
            const now = new Date();
            const daysSinceCreation = (now.getTime() - createdAt.getTime()) / (1000 * 60 * 60 * 24);
            if (daysSinceCreation > 5) {
                return res.status(403).json({ error: 'Email verification grace period expired (5 days)' });
            }
        }
        next();
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Server error checking verification' });
    }
};

module.exports = { verifyToken, requireEmailVerification };
