import { Connection, createConnection, ConnectionOptions } from 'typeorm';
import { ALL_ENTITIES } from '../entities/index';
import { logSystem } from './log';

function buildConfig(): ConnectionOptions {
    return {
        type: 'mysql',
        host: process.env.DB_HOST || 'play.southwest-roleplay.dev',
        port: Number(process.env.DB_PORT) || 3306,
        username: process.env.DB_USER || 'username',
        password: process.env.DB_PASS || 'password',
        database: process.env.DB_NAME || 'game',
        logging: ['error', 'log'],
        entities: ALL_ENTITIES as unknown as any[],
        synchronize: false,
    };
}

export class DatabaseSystem {
    connection?: Connection | void;
    attempts = 0;

    async init(): Promise<void> {
        const config = buildConfig();
        do {
            try {
                if (this.connection) {
                    await this.connection.connect();
                } else {
                    this.connection = await createConnection(config);
                }
            } catch (error) {
                if (this.attempts < 5) {
                    console.error(`[Bootstrap] Database connection unsuccessful, retrying ...`, error);
                    this.attempts++;
                } else {
                    console.error(`[Bootstrap] Database connection unsuccessful`, error);
                    process.exit();
                }
            }
        } while (!this.connection);

        logSystem.initLog('Database', 'Connection successful');
    }
}

export const databaseSystem = new DatabaseSystem();
