import mysql, { ServerlessMysql } from "serverless-mysql";

type Param = {
    /**
     * Read Only?
     */
    ro?: boolean;
    /**
     * Full Access?
     */
    fa?: boolean;
    /**
     * No Database Connection
     */
    noDb?: boolean;
    /**
     * Is this a local connection?
     */
    local?: boolean;
};

/**
 * # Grab General CONNECTION for DSQL
 */
export default function grabDSQLConnection(param?: Param): ServerlessMysql {
    if (global.DSQL_USE_LOCAL || param?.local) {
        return (
            global.DSQL_DB_CONN ||
            mysql({
                config: {
                    host: process.env.DSQL_DB_HOST,
                    user: process.env.DSQL_DB_USERNAME,
                    password: process.env.DSQL_DB_PASSWORD,
                    database: param?.noDb
                        ? undefined
                        : process.env.DSQL_DB_NAME,
                    port: process.env.DSQL_DB_PORT
                        ? Number(process.env.DSQL_DB_PORT)
                        : undefined,
                    charset: "utf8mb4",
                },
            })
        );
    }

    if (param?.ro) {
        return (
            global.DSQL_READ_ONLY_DB_CONN ||
            mysql({
                config: {
                    host: process.env.DSQL_DB_HOST,
                    user: process.env.DSQL_DB_READ_ONLY_USERNAME,
                    password: process.env.DSQL_DB_READ_ONLY_PASSWORD,
                    port: process.env.DSQL_DB_PORT
                        ? Number(process.env.DSQL_DB_PORT)
                        : undefined,
                    charset: "utf8mb4",
                },
            })
        );
    }

    if (param?.fa) {
        return (
            global.DSQL_FULL_ACCESS_DB_CONN ||
            mysql({
                config: {
                    host: process.env.DSQL_DB_HOST,
                    user: process.env.DSQL_DB_FULL_ACCESS_USERNAME,
                    password: process.env.DSQL_DB_FULL_ACCESS_PASSWORD,
                    port: process.env.DSQL_DB_PORT
                        ? Number(process.env.DSQL_DB_PORT)
                        : undefined,
                    charset: "utf8mb4",
                },
            })
        );
    }

    return (
        global.DSQL_DB_CONN ||
        mysql({
            config: {
                host: process.env.DSQL_DB_HOST,
                user: process.env.DSQL_DB_USERNAME,
                password: process.env.DSQL_DB_PASSWORD,
                database: param?.noDb ? undefined : process.env.DSQL_DB_NAME,
                port: process.env.DSQL_DB_PORT
                    ? Number(process.env.DSQL_DB_PORT)
                    : undefined,
                charset: "utf8mb4",
            },
        })
    );
}
