const postgres = require("postgres");
const { hash } = require("bcryptjs");
const crypto = require("node:crypto");

async function main() {
  const connectionString = process.env.DATABASE_URL?.trim();

  if (!connectionString) {
    throw new Error("DATABASE_URL is required");
  }

  const email = (
    process.env.SUPER_ADMIN_EMAIL || "superadmin@training-system.local"
  )
    .trim()
    .toLowerCase();
  const name = "Super Admin".trim();
  const password = "SuperAdmin123!".trim();

  if (password.length < 8) {
    throw new Error("SUPER_ADMIN_PASSWORD must be at least 8 characters");
  }

  const sql = postgres(connectionString, { prepare: false });

  try {
    const passwordHash = await hash(password, 10);
    const existingUser = await sql`
      select id
      from users
      where email = ${email}
      limit 1
    `;

    if (existingUser.length > 0) {
      await sql`
        update users
        set
          name = ${name},
          password_hash = ${passwordHash},
          system_role = 'super_admin',
          is_active = true,
          updated_at = now()
        where id = ${existingUser[0].id}
      `;

      console.log(`Updated existing super admin: ${email}`);
      return;
    }

    const userId = crypto.randomUUID();

    await sql`
      insert into users (
        id,
        name,
        email,
        password_hash,
        system_role,
        is_active
      )
      values (
        ${userId},
        ${name},
        ${email},
        ${passwordHash},
        'super_admin',
        true
      )
    `;

    console.log(`Created super admin: ${email}`);
  } finally {
    await sql.end({ timeout: 1 });
  }
}

main().catch((error) => {
  console.error("Failed to seed super admin.", error);
  process.exitCode = 1;
});
