#! /usr/bin/env node

import inquirer from "inquirer";
import fs from "fs";
import datasquirel from "..";
import { parseArgs } from "util";
import { DSQL_DatabaseSchemaType } from "../package-shared/types";
import dbSchemaToType from "../package-shared/functions/dsql/db-schema-to-type";
import path from "path";
import debugLog from "../package-shared/utils/logging/debug-log";
import parseEnv from "../package-shared/utils/parse-env";

const args = parseArgs({
    args: process.argv,
    options: {
        apiKey: {
            type: "string",
            default: process.env.DSQL_FULL_ACCESS_API_KEY,
            short: "k",
        },
        database: {
            type: "string",
            default: process.env.DSQL_DB_NAME,
            short: "d",
        },
        userid: {
            type: "string",
            default: process.env.DSQL_API_USER_ID,
            short: "i",
        },
        outfile: {
            type: "string",
            short: "o",
        },
        envfile: {
            type: "string",
            short: "e",
        },
        debug: {
            type: "boolean",
            short: "u",
        },
    },
    strict: false,
});

let appendedEnv: { [k: string]: string } = {};

if (args.values.envfile && typeof args.values.envfile == "string") {
    const finalEnvPath = path.resolve(process.cwd(), args.values.envfile);
    if (fs.existsSync(finalEnvPath)) {
        appendedEnv = parseEnv(finalEnvPath);

        if (args.values.debug) {
            debugLog({
                log: appendedEnv,
                label: "Appended env",
                title: "Schema to Typedef",
                addTime: true,
            });
        }
    }
}

const finalEnv = { ...process.env, ...appendedEnv } as { [k: string]: string };
process.env = { ...process.env, ...appendedEnv };

(async () => {
    try {
        const key = args.values.apiKey || finalEnv["DSQL_FULL_ACCESS_API_KEY"];
        const database = args.values.database || finalEnv["DSQL_DB_NAME"];
        const user_id =
            args.values.userid || finalEnv["DSQL_API_USER_ID"] || "1";

        if (args.values.debug) {
            debugLog({
                log: args.values,
                label: "Arguments",
                title: "Schema to Typedef",
                addTime: true,
            });
            debugLog({
                log: process.env.DSQL_FULL_ACCESS_API_KEY,
                label: "process.env.DSQL_FULL_ACCESS_API_KEY",
                title: "Schema to Typedef",
                addTime: true,
            });
            debugLog({
                log: process.env.DSQL_DB_NAME,
                label: "process.env.DSQL_DB_NAME",
                title: "Schema to Typedef",
                addTime: true,
            });
        }

        if (!database || typeof database !== "string")
            throw new Error("Database name is required");
        if (!key || typeof key !== "string")
            throw new Error("API key is required");
        if (!args.values.outfile || typeof args.values.outfile !== "string")
            throw new Error("Outfile are required");
        if (!user_id || typeof user_id !== "string")
            throw new Error("Outfile are required");

        const schema = await datasquirel.getSchema({
            key,
            database,
            user_id,
            env: finalEnv,
        });

        const dbSchema = schema.payload as DSQL_DatabaseSchemaType | undefined;

        if (args.values.debug) {
            debugLog({
                log: schema,
                label: "schema",
                title: "Schema to Typedef",
                addTime: true,
            });
        }

        if (!dbSchema) throw new Error("No schema found");

        const definitions = dbSchemaToType({ dbSchema });

        const finalOutfile = path.resolve(process.cwd(), args.values.outfile);
        const ourfileDir = path.dirname(finalOutfile);
        if (!fs.existsSync(ourfileDir)) {
            fs.mkdirSync(ourfileDir, { recursive: true });
        }

        fs.writeFileSync(
            finalOutfile,
            definitions?.join("\n\n") || "",
            "utf-8"
        );
    } catch (error: any) {
        debugLog({
            log: error.message,
            label: "Error",
            title: "Schema to Typedef",
            addTime: true,
            type: "error",
        });
        process.exit(1);
    }
})();