const bcrypt = require("bcrypt");
const db = require("../config/db");

module.exports = async function bootstrapAdmin() {

    const username =
        process.env.ADMIN_USERNAME;

    const email =
        process.env.ADMIN_EMAIL;

    const password =
        process.env.ADMIN_PASSWORD;

    const [rows] = await db.query(

        `
        SELECT id
        FROM users
        WHERE username = ?
        LIMIT 1
        `,

        [username]

    );

    if (rows.length > 0) {

        console.log("✓ Administrator already exists.");

        return;

    }

    const hashedPassword =
        await bcrypt.hash(password, 12);

    await db.query(

        `
        INSERT INTO users
        (
            full_name,
            username,
            email,
            phone,
            password,
            role_id,
            status,
            created_at
        )
        VALUES
        (
            ?,
            ?,
            ?,
            ?,
            ?,
            ?,
            ?,
            NOW()
        )
        `,

        [

            "System Administrator",

            username,

            email,

            "",

            hashedPassword,

            1,

            "active"

        ]

    );

    console.log("✓ Default administrator created.");

};