// @ts-check

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

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

import grabDbSSL from "../package-shared/utils/backend/grabDbSSL";
import mysql from "serverless-mysql";

const connection = mysql({
    config: {
        host: process.env.DSQL_DB_HOST,
        user: process.env.DSQL_DB_USERNAME,
        password: process.env.DSQL_DB_PASSWORD,
        database: process.env.DSQL_DB_NAME,
        charset: "utf8mb4",
        ssl: grabDbSSL(),
    },
});

const tableIndex = process.argv.findIndex((str) => str.match(/--table|-t/));
const table = tableIndex >= 0 ? process.argv[tableIndex + 1] : null;

if (!table) {
    console.log(
        "Please add a table flag to the arguments: Eg. '--talbe <table_name>'"
    );
    process.exit();
}

connection
    .query("SHOW COLUMNS FROM" + " " + table)
    .then((result: any) => {
        let typedefStart = `/**\n * @typedef {object} MYSQL_${table}_table_def\n`;
        let typedefMid = "";
        let typedefEnd = ` */`;
        console.log("Result =>", result);

        result.forEach((res: any) => {
            const parsedResult = JSON.parse(JSON.stringify(res));
            const { Field, Type, Null, Key, Default, Extra } = parsedResult;
            const type = (() => {
                if (Type?.match(/int/i)) return "number";
                return "string";
            })();
            typedefMid += ` * @property {${type}} [${Field}] - NULL=\`${Null}\` Key=\`${Key}\` Default=\`${Default}\` Extra=\`${Extra}\`\n`;
        });

        console.log(typedefStart + typedefMid + typedefEnd);

        process.exit();
    })
    .catch((error) => {
        console.log(error.message);
    })
    .finally(() => {
        /** ********************* Clean up */
        connection.end();
    });
