/**
 * Create or promote an admin user. Loads env from src/config/.env
 *
 * Usage:
 *   npm run seed:admin
 *
 * Requires in .env (or shell):
 *   DB_URI, SALT (same as app; bcrypt salt rounds string)
 *   ADMIN_EMAIL, ADMIN_PASSWORD
 */
import path from "path";
import dotenv from "dotenv";

dotenv.config({ path: path.join(__dirname, "..", "config", ".env") });

import mongoose from "mongoose";
import { hash } from "bcrypt";
import UserModel from "../models/UserModel";
import { ROLE } from "../constants/enums";

function escapeRegex(s: string) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

async function main() {
  const emailRaw = process.env.ADMIN_EMAIL?.trim();
  const password = process.env.ADMIN_PASSWORD;
  const dbUri = process.env.DB_URI;
  const salt = process.env.SALT;

  if (!emailRaw || !password) {
    console.error(
      "Set ADMIN_EMAIL and ADMIN_PASSWORD (e.g. in src/config/.env) before running."
    );
    process.exit(1);
  }
  if (!dbUri) {
    console.error("DB_URI is missing.");
    process.exit(1);
  }
  if (!salt) {
    console.error("SALT is missing (required for bcrypt, same as app signup).");
    process.exit(1);
  }

  const emailLower = emailRaw.toLowerCase();

  await mongoose.connect(dbUri);
  const hashed = await hash(password, String(salt));

  const existing = await UserModel.findOne({
    email: { $regex: new RegExp(`^${escapeRegex(emailRaw)}$`, "i") },
  });

  if (existing) {
    await UserModel.findByIdAndUpdate(existing._id, {
      email: emailLower,
      password: hashed,
      userType: ROLE.ADMIN,
      isVerified: true,
      isProfileCompleted: true,
      isCarsRegistered: true,
      isBanned: false,
      isDeleted: false,
    });
    console.log(`Updated existing user to admin: ${emailLower}`);
  } else {
    await UserModel.create({
      email: emailLower,
      password: hashed,
      userType: ROLE.ADMIN,
      isVerified: true,
      isProfileCompleted: true,
      isCarsRegistered: true,
      isBanned: false,
      isDeleted: false,
    });
    console.log(`Created admin user: ${emailLower}`);
  }

  await mongoose.disconnect();
  process.exit(0);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
