#!/usr/bin/env tsx
/**
 * Admin User Seed Script
 *
 * Creates an admin user for staff dashboard access.
 * Usage: npx tsx scripts/create-admin.ts <username> <password> [email] [name]
 *
 * Example: npx tsx scripts/create-admin.ts admin SecurePass123! admin@mawidi.com "Admin User"
 */

import { prisma } from "../lib/db";
import bcrypt from "bcryptjs";
import { createId } from "@paralleldrive/cuid2";

async function main() {
  const args = process.argv.slice(2);

  if (args.length < 2) {
    console.error(
      "Usage: npx tsx scripts/create-admin.ts <username> <password> [email] [name]",
    );
    process.exit(1);
  }

  const [username, password, email = `${username}@mawidi.local`, name = username] =
    args;

  // Check if user already exists
  const existing = await prisma.users.findFirst({
    where: {
      OR: [{ username }, { email }],
    },
  });

  if (existing) {
    console.log(`User already exists: ${existing.username} (${existing.email})`);
    console.log(`Current role: ${existing.role}`);

    // Update role to ADMIN if not already
    if (existing.role !== "ADMIN" && existing.role !== "SUPER_ADMIN") {
      await prisma.users.update({
        where: { id: existing.id },
        data: { role: "ADMIN", isActive: true },
      });
      console.log("Updated role to ADMIN");
    }

    // Update password if provided
    const hashedPassword = await bcrypt.hash(password, 12);
    await prisma.users.update({
      where: { id: existing.id },
      data: { password: hashedPassword },
    });
    console.log("Password updated");

    return;
  }

  // Create new admin user
  const hashedPassword = await bcrypt.hash(password, 12);
  const userId = createId();

  const user = await prisma.users.create({
    data: {
      id: userId,
      username,
      email,
      name,
      password: hashedPassword,
      role: "ADMIN",
      isActive: true,
      failedAttempts: 0,
      loginCount: 0,
      onboardingComplete: true,
      whatsappConnected: false,
    },
  });

  console.log("Admin user created successfully:");
  console.log(`  ID:       ${user.id}`);
  console.log(`  Username: ${user.username}`);
  console.log(`  Email:    ${user.email}`);
  console.log(`  Name:     ${user.name}`);
  console.log(`  Role:     ${user.role}`);
  console.log("");
  console.log(`Login at: http://localhost:9000/staff/login`);
}

main()
  .catch((err) => {
    console.error("Failed to create admin user:", err);
    process.exit(1);
  })
  .finally(() => {
    prisma.$disconnect();
  });
