require("dotenv").config();
const { Users, Companies, Subscriptions } = require("../models");
const { hash } = require("bcryptjs");
const sequelize = require("../db");

async function createSuperAdmin() {
  const password = process.argv[2];
  if (!password) {
    console.error("Usage: node scripts/createSuperAdmin.js <password>");
    process.exit(1);
  }
  try {
    await sequelize.authenticate();
    let company = await Companies.findOne({
      where: { email: "ahmad.alhaffar@nordsafe-ehs.com" },
    });
    if (!company) {
      company = await Companies.create({
        name: "NordSafe EHS",
        email: "ahmad.alhaffar@nordsafe-ehs.com",
        country: "NO",
        subscriptionType: "paid",
        subscriptionEndsAt: new Date("2099-12-31"),
      });
      await Subscriptions.create({
        CompanyId: company.id,
        usersCount: 9999,
        projectsCount: 9999,
        monthlySDSSearchCount: 9999,
        monthlySDSSaveCount: 9999,
        subscriptionType: "paid",
        subscriptionEndsAt: new Date("2099-12-31"),
      });
    }
    const existing = await Users.findOne({
      where: { email: "ahmad.alhaffar@nordsafe-ehs.com" },
    });
    if (existing) {
      await Users.update(
        { role: "super-admin" },
        { where: { email: "ahmad.alhaffar@nordsafe-ehs.com" } },
      );
      console.log("✅ Role updated to super-admin");
      process.exit(0);
    }
    const hashed = await hash(password, 10);
    await Users.create({
      fullname: "Ahmad Alhaffar",
      email: "ahmad.alhaffar@nordsafe-ehs.com",
      password: hashed,
      role: "super-admin",
      department: "Management",
      jobDesc: "System Owner",
      CompanyId: company.id,
    });
    console.log("✅ Super admin created successfully!");
    process.exit(0);
  } catch (err) {
    console.error("❌ Error:", err.message);
    process.exit(1);
  }
}

createSuperAdmin();
