/**
 * Test script to verify JWT tokens are unique even for the same user
 * Run: node test-token-uniqueness.js
 */

import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();

const JWT_SECRET = process.env.JWT_SECRET;

console.log('='.repeat(60));
console.log('JWT TOKEN UNIQUENESS TEST');
console.log('='.repeat(60));

// Simulate the same user logging in multiple times
const sameUser = {
  userId: '68e898d36645a66c6f3940b1',
  email: 'developer0031@gmail.com',
  userName: 'Developer'
};

console.log('\n📝 Testing: Same user logging in 3 times\n');

// Generate 3 tokens for the same user
const tokens = [];
for (let i = 1; i <= 3; i++) {
  // Delay to ensure different timestamps (JWT iat has 1-second precision)
  if (i > 1) await new Promise(resolve => setTimeout(resolve, 1100));
  
  const token = jwt.sign(
    { 
      userId: sameUser.userId, 
      email: sameUser.email, 
      userName: sameUser.userName 
    },
    JWT_SECRET,
    { expiresIn: '7d' }
  );
  
  tokens.push(token);
  
  // Decode to show contents
  const decoded = jwt.decode(token);
  
  console.log(`Login ${i}:`);
  console.log(`  Token: ${token.substring(0, 50)}...`);
  console.log(`  Issued At (iat): ${decoded.iat} (${new Date(decoded.iat * 1000).toISOString()})`);
  console.log(`  Expires At (exp): ${decoded.exp} (${new Date(decoded.exp * 1000).toISOString()})`);
  console.log(`  User ID: ${decoded.userId}`);
  console.log();
}

// Verify all tokens are different
console.log('🔍 VERIFICATION:');
console.log(`Token 1 === Token 2? ${tokens[0] === tokens[1] ? '❌ SAME (BAD!)' : '✅ DIFFERENT (GOOD!)'}`);
console.log(`Token 2 === Token 3? ${tokens[1] === tokens[2] ? '❌ SAME (BAD!)' : '✅ DIFFERENT (GOOD!)'}`);
console.log(`Token 1 === Token 3? ${tokens[0] === tokens[2] ? '❌ SAME (BAD!)' : '✅ DIFFERENT (GOOD!)'}`);

console.log('\n' + '='.repeat(60));
console.log('CONCLUSION:');
console.log('Each login generates a UNIQUE token due to different iat timestamp.');
console.log('Even for the same user, tokens are NEVER identical.');
console.log('='.repeat(60));
