/* eslint-disable @typescript-eslint/no-explicit-any */
import mysql from 'mysql2/promise';

// Configuration for Docker environment (when app runs in container)
const dockerConfig = {
    host: process.env.DB_HOST || 'nordicstorium-db',
    port: parseInt(process.env.DB_PORT || '3306'),
    user: process.env.DB_USER || 'nordic_app_user',
    password: process.env.DB_PASSWORD, // NEVER hardcode passwords here
    database: process.env.DB_NAME || 'nordic_storium',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
    charset: 'utf8mb4',
    timezone: 'Z',
    enableKeepAlive: true,
    keepAliveInitialDelay: 0,
    decimalNumbers: true,
    supportBigNumbers: true,
    bigNumberStrings: true,
    // Enable SSL if needed
    ssl: process.env.DB_SSL === 'true' ? {
        rejectUnauthorized: false
    } : undefined
};

// Configuration for local development (outside Docker)
const localConfig = {
    ...dockerConfig,
    host: 'localhost',
};

// Check if we're running in Docker
const isDocker = process.env.IN_DOCKER === 'true' ||
    process.env.DB_HOST === 'nordicstorium-db';

// Use appropriate configuration
const config = isDocker ? dockerConfig : localConfig;

// Use a global variable to preserve the pool across HMR reloads in development
const globalForDb = globalThis as unknown as {
    pool: mysql.Pool | undefined;
};

// Create the connection pool (Singleton pattern for Next.js HMR)
const pool = globalForDb.pool ?? mysql.createPool(config);

if (process.env.NODE_ENV !== 'production') {
    globalForDb.pool = pool;
}

// Test connection function
export async function testConnection() {
    let connection;
    try {
        connection = await pool.getConnection();
        console.log('✅ Database connection successful!');

        // Get database info
        const [dbInfo]: any = await connection.query(
            'SELECT DATABASE() as db, USER() as user, VERSION() as version'
        );

        console.log('📊 Database Info:', dbInfo[0]);

        return {
            success: true,
            message: 'Database connected successfully',
            info: dbInfo[0],
            config: {
                host: config.host,
                port: config.port,
                database: config.database,
                user: config.user,
                environment: process.env.NODE_ENV,
                inDocker: isDocker,
            }
        };
    } catch (error: any) {
        console.error('❌ Database connection failed:', {
            message: error.message,
            code: error.code,
            errno: error.errno,
            sqlState: error.sqlState,
        });

        return {
            success: false,
            error: {
                message: error.message,
                code: error.code,
                errno: error.errno,
                sqlState: error.sqlState,
            },
            config: {
                host: config.host,
                port: config.port,
                database: config.database,
                user: config.user,
            }
        };
    } finally {
        if (connection) connection.release();
    }
}

// Export the pool and helper functions
export default pool;

export async function query(sql: string, params: any[] = []) {
    const [rows] = await pool.execute(sql, params);
    return rows;
}

export async function getConnection() {
    return await pool.getConnection();
}

export async function executeTransaction<T>(
    callback: (connection: mysql.PoolConnection) => Promise<T>
): Promise<T> {
    const connection = await pool.getConnection();
    try {
        await connection.beginTransaction();
        const result = await callback(connection);
        await connection.commit();
        return result;
    } catch (error) {
        await connection.rollback();
        throw error;
    } finally {
        connection.release();
    }
}