const { Pool } = require("pg");
const bcrypt = require("bcrypt");
const { v4: uuid } = require("uuid");

const pool = new Pool({
  host: process.env.PGHOST || "localhost",
  port: parseInt(process.env.PGPORT || "5432"),
  database: process.env.PGDATABASE || "atapoly_cbt",
  user: process.env.PGUSER || "cbt_admin",
  password: process.env.PGPASSWORD || "cbt_password",
});

async function seed() {
  const client = await pool.connect();

  try {
    await client.query("BEGIN");

    console.log("🚀 Seeding ONLY super admin...");

    // Super Admin ONLY
    const adminHash = await bcrypt.hash("admin123", 10);
    const adminId = uuid();

    const result = await client.query(
      `INSERT INTO users (id, name, email, password_hash, role)
       VALUES ($1, $2, $3, $4, $5)
       ON CONFLICT (email) DO NOTHING
       RETURNING id`,
      [
        adminId,
        "System Administrator",
        "admin@cbt.edu.ng",
        adminHash,
        "super_admin",
      ],
    );

    if (result.rowCount === 0) {
      console.log("ℹ️ Super admin already exists, skipping insert");
    } else {
      console.log("✅ Super admin created");
    }

    await client.query("COMMIT");
    console.log("🎉 Seed completed successfully (admin only)");
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("❌ Seed failed:", err.message);
    throw err;
  } finally {
    client.release();
    await pool.end();
  }
}

seed()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error("❌ Fatal error:", err.message);
    process.exit(1);
  });
