const bcrypt = require("bcrypt");
const { query } = require("./config/database");

async function createTempAdmin() {
  try {
    // Temporary credentials
    const email = "admin@skyartshop.com";
    const password = "TempAdmin2024!";
    const name = "Temporary Admin";
    const role = "superadmin";

    // Hash the password
    const passwordHash = await bcrypt.hash(password, 10);

    // Check if user already exists
    const existing = await query("SELECT id FROM adminusers WHERE email = $1", [
      email,
    ]);

    if (existing.rows.length > 0) {
      console.log("⚠️  Admin user already exists. Updating password...");
      await query(
        "UPDATE adminusers SET passwordhash = $1, name = $2, role = $3 WHERE email = $4",
        [passwordHash, name, role, email]
      );
      console.log("✓ Password updated successfully!");
    } else {
      // Create the admin user
      await query(
        `INSERT INTO adminusers (email, name, passwordhash, role, createdat) 
         VALUES ($1, $2, $3, $4, NOW())`,
        [email, name, passwordHash, role]
      );
      console.log("✓ Temporary admin user created successfully!");
    }

    console.log("\n========================================");
    console.log("TEMPORARY ADMIN CREDENTIALS");
    console.log("========================================");
    console.log("Email:    ", email);
    console.log("Password: ", password);
    console.log("========================================");
    console.log("\n⚠️  IMPORTANT: Change this password after first login!\n");

    process.exit(0);
  } catch (error) {
    console.error("Error creating admin user:", error);

    if (error.code === "42P01") {
      console.error('\n❌ Table "adminusers" does not exist.');
      console.error("Please create the database schema first.");
      console.log("\nRun this SQL to create the table:");
      console.log(`
CREATE TABLE IF NOT EXISTS adminusers (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  passwordhash TEXT NOT NULL,
  role VARCHAR(50) DEFAULT 'admin',
  createdat TIMESTAMP DEFAULT NOW(),
  lastlogin TIMESTAMP
);
      `);
    }

    process.exit(1);
  }
}

createTempAdmin();
