import 'dotenv/config';
import prisma from './lib/prisma';
import bcrypt from 'bcryptjs';

async function main() {
  const users = await prisma.user.findMany();
  console.log("Users in DB:", users.length);
  for (const u of users) {
    console.log(`- ID: ${u.id}, Username: ${u.username}`);
  }

  if (users.length > 0) {
    // Force reset the password of the first user to what's in .env just in case
    const username = process.env.ADMIN_USERNAME || "admin";
    const password = process.env.ADMIN_PASSWORD || "secretpassword";
    console.log(`Updating password for user ${username} to ${password}...`);
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // Check if the exact user exists
    const exactUser = await prisma.user.findUnique({ where: { username } });
    if (exactUser) {
      await prisma.user.update({
        where: { username },
        data: { password: hashedPassword }
      });
      console.log(`Password reset successfully for ${username}.`);
    } else {
      console.log(`No exact user found with username ${username}. Updating first user.`);
      await prisma.user.update({
        where: { id: users[0].id },
        data: { username: username, password: hashedPassword }
      });
      console.log(`Updated first user to be ${username} with new password.`);
    }
  } else {
    console.log("No users exist in DB. The auth code will create one automatically.");
  }
}

main()
  .catch(e => console.error(e))
  .finally(() => prisma.$disconnect());
