"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("dotenv/config");
require("reflect-metadata");
const promise_1 = __importDefault(require("mysql2/promise"));
const env_1 = require("../main/config/env");
const data_source_1 = require("../infrastructure/persistence/data-source");
const redis_client_1 = require("../infrastructure/cache/redis-client");
const mysqlConnectionOptions = {
    host: env_1.env.DB_HOST,
    port: env_1.env.DB_PORT,
    user: env_1.env.DB_USER,
    password: env_1.env.DB_PASS,
};
const createDatabaseIfNotExists = async () => {
    const connection = await promise_1.default.createConnection(mysqlConnectionOptions);
    try {
        await connection.query('CREATE DATABASE IF NOT EXISTS ?? CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci', [env_1.env.DB_NAME]);
    }
    finally {
        await connection.end();
    }
};
const databaseHasTables = async () => {
    const connection = await promise_1.default.createConnection({
        ...mysqlConnectionOptions,
        database: env_1.env.DB_NAME,
    });
    try {
        const [rows] = await connection.query('SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ?', [env_1.env.DB_NAME]);
        return Number(rows[0]?.count ?? 0) > 0;
    }
    finally {
        await connection.end();
    }
};
const run = async () => {
    await createDatabaseIfNotExists();
    const hasTables = await databaseHasTables();
    if (hasTables) {
        // eslint-disable-next-line no-console
        console.info('Database already exists and has tables; skipping schema build.');
    }
    else {
        await (0, data_source_1.initializeDatabase)();
        if (!data_source_1.AppDataSource.options.synchronize) {
            await (0, data_source_1.runMigrations)();
        }
    }
    await redis_client_1.redisClient.quit();
    process.exit(0);
};
run().catch((error) => {
    // eslint-disable-next-line no-console
    console.error('Database setup failed', error);
    process.exit(1);
});
//# sourceMappingURL=setup-database.js.map