
import { storage } from "../server/storage";
import { scrypt, randomBytes } from "crypto";
import { promisify } from "util";

const scryptAsync = promisify(scrypt);

async function hashPassword(password: string) {
    const salt = randomBytes(16).toString("hex");
    const buf = (await scryptAsync(password, salt, 64)) as Buffer;
    return `${buf.toString("hex")}.${salt}`;
}

async function run() {
    try {
        console.log("🔍 Checking for 'admin' user...");
        let user = await storage.getUserByUsername("admin");

        const password = "admin";
        console.log(`🔐 Hashing password '${password}'...`);
        const hashedPassword = await hashPassword(password);

        if (user) {
            console.log(`✅ User 'admin' found (ID: ${user.id}). Updating credentials...`);
            await storage.updateUser(user.id, {
                password: hashedPassword,
                role: 'admin',
                isActive: true,
                aiEnabled: true,
                is2faEnabled: false
            });
            console.log("✅ Admin user updated successfully.");
        } else {
            console.log("⚠️ User 'admin' not found. Checking by email 'admin@example.com'...");
            const emailUser = await storage.getUserByEmail("admin@example.com");

            if (emailUser) {
                console.log(`✅ User found by email (ID: ${emailUser.id}). Updating to username 'admin'...`);
                await storage.updateUser(emailUser.id, {
                    username: "admin",
                    password: hashedPassword,
                    role: "admin",
                    isActive: true,
                    aiEnabled: true,
                    showOnLeaderboard: false,
                    isSearchable: false
                });
                console.log("✅ Admin user updated/renamed successfully.");
            } else {
                console.log("🆕 Creating new 'admin' user...");
                await storage.createUser({
                    username: "admin",
                    email: "admin@example.com",
                    password: hashedPassword,
                    role: "admin",
                    isActive: true,
                    showOnLeaderboard: false,
                    isSearchable: false,
                    // aiEnabled defaults to true in schema/storage if omitted in Insert, 
                    // but depending on implementation might need it.
                    // Storage implementation handles defaults if not provided?
                    // Let's pass defaults we know are safe.
                } as any); // cast as any to avoid strict InsertUser type mismatches if interfaces drift
                console.log("✅ Admin user created successfully.");
            }
        }
        process.exit(0);
    } catch (e) {
        console.error("❌ Failed to create/update admin user:", e);
        process.exit(1);
    }
}

run();
