import fs from "fs";
import path from "path";

export const grabAuthDirs = () => {
    const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
    const ROOT_DIR = DSQL_AUTH_DIR?.match(/./)
        ? DSQL_AUTH_DIR
        : path.resolve(process.cwd(), "./.tmp");
    const AUTH_DIR = path.join(ROOT_DIR, "logins");

    return { root: ROOT_DIR, auth: AUTH_DIR };
};

export const initAuthFiles = () => {
    try {
        const authDirs = grabAuthDirs();

        if (!fs.existsSync(authDirs.root))
            fs.mkdirSync(authDirs.root, { recursive: true });
        if (!fs.existsSync(authDirs.auth))
            fs.mkdirSync(authDirs.auth, { recursive: true });
        return true;
    } catch (error: any) {
        console.log(`Error initializing Auth Files: ${error.message}`);
        return false;
    }
};

/**
 * # Write Auth Files
 */
export const writeAuthFile = (name: string, data: string) => {
    initAuthFiles();
    try {
        fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
        return true;
    } catch (/** @type {any} */ error: any) {
        console.log(`Error writing Auth File: ${error.message}`);
        return false;
    }
};

/**
 * # Get Auth Files
 */
export const getAuthFile = (name: string) => {
    try {
        const authFilePath = path.join(grabAuthDirs().auth, name);
        return fs.readFileSync(authFilePath, "utf-8");
    } catch (/** @type {any} */ error: any) {
        console.log(`Error getting Auth File: ${error.message}`);
        return null;
    }
};

/**
 * # Delete Auth Files
 * @param {string} name
 */
export const deleteAuthFile = (name: string) => {
    try {
        return fs.rmSync(path.join(grabAuthDirs().auth, name));
    } catch (/** @type {any} */ error: any) {
        console.log(`Error deleting Auth File: ${error.message}`);
        return null;
    }
};

/**
 * # Delete Auth Files
 * @param {string} name
 */
export const checkAuthFile = (name: string) => {
    try {
        return fs.existsSync(path.join(grabAuthDirs().auth, name));
        return true;
    } catch (/** @type {any} */ error: any) {
        console.log(`Error checking Auth File: ${error.message}`);
        return false;
    }
};