import bcrypt from "bcryptjs";
import mysql from "mysql2/promise";
import dotenv from "dotenv";
import path from "path";

dotenv.config({ path: path.resolve('backend/.env') });

const dbConfig = {
  host: process.env.DB_HOST || "127.0.0.1",
  port: Number(process.env.DB_PORT || 3306),
  database: process.env.DB_NAME || "e_notary",
  user: process.env.DB_USER || "root",
  password: process.env.DB_PASSWORD || ""
};

const demoAccounts = [
  { email: "admin@enotary.gov", password: "admin123" },
  { email: "justice@enotary.gov", password: "justice123" },
  { email: "finance@enotary.gov", password: "finance123" },
  { email: "owner@notary.so", password: "owner123" },
  { email: "teller@notary.so", password: "teller123" },
  { email: "payment@notary.so", password: "payment123" },
  { email: "executive@notary.so", password: "exec123" }
];

async function fixHashes() {
  let connection;
  try {
    console.log("Connecting to database...", dbConfig.database);
    connection = await mysql.createConnection(dbConfig);
    
    for (const account of demoAccounts) {
      console.log(`Hashing password for ${account.email}...`);
      const hash = await bcrypt.hash(account.password, 10);
      
      const [result] = await connection.execute(
        "UPDATE users SET password_hash = ? WHERE email = ?",
        [hash, account.email]
      );
      
      if (result.affectedRows > 0) {
        console.log(`Successfully updated ${account.email}`);
      } else {
        console.log(`User ${account.email} not found in database.`);
      }
    }
    
    console.log("All demo accounts processed.");
  } catch (error) {
    console.error("Error fixing hashes:", error);
  } finally {
    if (connection) await connection.end();
  }
}

fixHashes();
