import path from "path";
require("dotenv").config({ path: path.resolve(__dirname, ".env") });

import fs from "fs";
import { execSync } from "child_process";

/**
 * # Create Extra users
 * @description Create `READ_ONLY` and `FULL_ACCESS` users
 */
async function initRootUser() {
    /**
     * Grab Schema
     *
     * @description Grab Schema
     */
    const first_name = process.env.DSQL_LOCAL_SU_FIRST_NAME;
    const last_name = process.env.DSQL_LOCAL_SU_LAST_NAME;
    const email = process.env.DSQL_LOCAL_SU_EMAIL;
    const username = process.env.DSQL_LOCAL_SU_USERNAME;
    const password = process.env.DSQL_LOCAL_SU_PASSWORD;

    if (!password) {
        throw new Error("Please enter a root admin user password");
    }

    /** @type {any} */
    const userObject = {
        id: 1,
        first_name,
        last_name,
        username,
        email,
        password,
        verification_status: 1,
        user_priviledge: 7,
    };

    try {
        const tmpDir = "/app/.tmp";
        if (!fs.existsSync(tmpDir)) {
            fs.mkdirSync(tmpDir, { recursive: true });
        }
        const tmpFilePath = `${tmpDir}/new-user.json`;
        fs.writeFileSync(tmpFilePath, JSON.stringify(userObject));
        const execStr = `bun /app/package-shared/shell/mariadb-users/users/create-user.ts ${tmpFilePath}`;
        execSync(execStr, { stdio: "inherit" });
    } catch (error: any) {
        console.log(`docker-root-user-init.ts ERROR: ${error.message}`);
    }

    process.exit();
}

initRootUser();
