import fs from "fs";
import path from "path";
import EJSON from "../../../utils/ejson";
import { DATASQUIREL_LoggedInUser } from "../../../types";
import debugLog from "../../../utils/logging/debug-log";

function debugFn(log: any, label?: string) {
    debugLog({ log, addTime: true, title: "write-auth-files", label });
}

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}`);
        global.ERROR_CALLBACK?.(
            `Error Initializing Auth Files`,
            error as Error
        );
        return false;
    }
};

/**
 * # Write Auth Files
 */
export const writeAuthFile = (
    name: string,
    data: string,
    cleanup?: {
        userId: string | number;
    }
) => {
    initAuthFiles();

    try {
        const { auth } = grabAuthDirs();
        if (cleanup) {
            cleanupUserAuthFiles(cleanup.userId);
        }
        fs.writeFileSync(path.join(auth, name), data);
        return true;
    } catch (error: any) {
        console.log(`Error writing Auth File: ${error.message}`);
        return false;
    }
};

/**
 * # Clean up User Auth Files
 */
export const cleanupUserAuthFiles = (userId: string | number) => {
    initAuthFiles();
    try {
        const { auth } = grabAuthDirs();
        const loginFiles = fs.readdirSync(auth);
        for (let i = 0; i < loginFiles.length; i++) {
            const loginFile = loginFiles[i];
            const loginFilePath = path.join(auth, loginFile);

            try {
                const authPayload = EJSON.parse(
                    fs.readFileSync(loginFilePath, "utf-8")
                ) as DATASQUIREL_LoggedInUser;

                if (authPayload.id == userId) {
                    fs.unlinkSync(loginFilePath);
                }
            } catch (error: any) {}
        }
        return true;
    } catch (error: any) {
        console.log(`Error Cleaning up User Auth Files: ${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 (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 (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 (error: any) {
        console.log(`Error checking Auth File: ${error.message}`);
        return false;
    }
};