#! /usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = run;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
require("dotenv").config({
    path: path_1.default.resolve(process.cwd(), ".env"),
});
const index_1 = __importDefault(require("../index"));
const console_colors_1 = __importDefault(require("../console-colors"));
const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema"));
if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) {
    console.log(".env file not found");
    process.exit();
}
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
if (!(DSQL_HOST === null || DSQL_HOST === void 0 ? void 0 : DSQL_HOST.match(/./))) {
    console.log("DSQL_HOST is required in your `.env` file");
    process.exit();
}
if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./))) {
    console.log("DSQL_USER is required in your `.env` file");
    process.exit();
}
if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) {
    console.log("DSQL_PASS is required in your `.env` file");
    process.exit();
}
const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
function run() {
    return __awaiter(this, void 0, void 0, function* () {
        let schemaData;
        if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
            const dbSchemaDataResponse = yield index_1.default.getSchema({
                key: DSQL_KEY,
                database: DSQL_REF_DB_NAME || undefined,
            });
            if (!dbSchemaDataResponse.payload ||
                Array.isArray(dbSchemaDataResponse.payload)) {
                console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
                console.log(dbSchemaDataResponse);
                process.exit();
            }
            let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
            if (DSQL_DB_NAME)
                fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
            schemaData = [fetchedDbSchemaObject];
        }
        else if (DSQL_KEY) {
            const dbSchemaDataResponse = yield index_1.default.getSchema({
                key: DSQL_KEY,
                database: DSQL_REF_DB_NAME || undefined,
            });
            if (!dbSchemaDataResponse.payload ||
                !Array.isArray(dbSchemaDataResponse.payload)) {
                console.log("DSQL_KEY => Error in fetching DB schema");
                console.log(dbSchemaDataResponse);
                process.exit();
            }
            let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
            // fetchedDbSchemaObject.forEach((db, index) => {
            //     db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
            // });
            schemaData = fetchedDbSchemaObject;
        }
        else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) {
            schemaData = [
                JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")),
            ];
        }
        else {
            console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
            process.exit();
        }
        if (!schemaData) {
            console.log("No schema found");
            process.exit();
        }
        if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
            fs_1.default.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
        }
        console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`);
        yield (0, createDbFromSchema_1.default)({
            dbSchemaData: schemaData,
        });
        console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`);
    });
}
let interval;
if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
    fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
        console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`);
        run();
    });
}
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
    interval = setInterval(() => {
        console.log(` - ${console_colors_1.default.FgMagenta}Info:${console_colors_1.default.Reset} Syncing Databases from the cloud ...`);
        run();
    }, 20000);
}
run();