/**
 * Interactive password reset script
 *
 * USAGE:
 * 1. Open a terminal in the memento-note directory
 * 2. Run: node scripts/reset-password.js
 * 3. Enter the email of the account to reset
 * 4. Enter the new password (twice for confirmation)
 * 5. Done! Log in with the new password
 */

const readline = require('readline');
const bcrypt = require('bcryptjs');
const prisma = require('../lib/prisma').default;

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('================================================================');
console.log('              INTERACTIVE PASSWORD RESET');
console.log('');
console.log('  WARNING: Use only for your own account!');
console.log('');
console.log('================================================================');
console.log('');

rl.question('Enter the EMAIL of the account to reset: ', async (email) => {
  if (!email || !email.includes('@')) {
    console.log('Error: Invalid email!');
    rl.close();
    process.exit(1);
  }

  email = email.toLowerCase().trim();

  console.log(`Looking up account: ${email}...`);

  try {
    const user = await prisma.user.findUnique({
      where: { email: email }
    });

    if (!user) {
      console.log('');
      console.log('ERROR: No account found with this email!');
      console.log('');
      console.log('AVAILABLE ACCOUNTS (if any):');
      console.log('-------------------------');

      const allUsers = await prisma.user.findMany({
        select: { email: true, name: true, role: true, createdAt: true },
        orderBy: { createdAt: 'desc' }
      });

      if (allUsers.length > 0) {
        console.log('');
        allUsers.forEach((u, index) => {
          console.log(`${index + 1}. Email: ${u.email}`);
          console.log(`   Name: ${u.name || 'N/A'}`);
          console.log(`   Role: ${u.role}`);
          console.log(`   Created: ${u.createdAt.toLocaleString()}`);
          console.log('');
        });
      } else {
        console.log('   (No accounts in the database)');
      }

      console.log('-------------------------');
      console.log('');
      rl.close();
      process.exit(1);
    }

    console.log(`Account found: ${user.email} (${user.name})`);
    console.log('');

    rl.question('Enter the NEW password (minimum 6 characters): ', async (newPassword) => {
      if (!newPassword || newPassword.length < 6) {
        console.log('Error: Password must be at least 6 characters!');
        rl.close();
        process.exit(1);
      }

      rl.question('Confirm the new password: ', async (confirmPassword) => {
        if (newPassword !== confirmPassword) {
          console.log('Error: Passwords do not match!');
          rl.close();
          process.exit(1);
        }

        console.log('');
        console.log('Resetting password...');

        const hashedPassword = await bcrypt.hash(newPassword, 10);

        await prisma.user.update({
          where: { id: user.id },
          data: {
            password: hashedPassword,
            resetToken: null,
            resetTokenExpiry: null
          }
        });

        console.log('SUCCESS! Password has been reset!');
        console.log('');
        console.log('================================================================');
        console.log('YOU CAN NOW LOG IN!');
        console.log('================================================================');
        console.log('');
        console.log('Login URL: http://localhost:3000/login');
        console.log('Email:', email);
        console.log('Password:', newPassword);
        console.log('');

        rl.close();
        process.exit(0);
      });
    });
  } catch (error) {
    console.log('');
    console.log('ERROR during password reset:');
    console.error(error);
    rl.close();
    process.exit(1);
  }
});
