import knex from 'knex';
import databaseConfig from '../../config/database';
import logger from '../../config/logger';

// Create a knex instance with the appropriate configuration
export const db = knex(databaseConfig);

/**
 * Test the database connection
 * @returns {Promise<boolean>} True if connection is successful, otherwise throws error
 */
export const testConnection = async (): Promise<boolean> => {
  try {
    // Attempt to connect and run a simple query
    await db.raw('SELECT 1');
    logger.info('Database connection successful');
    return true;
  } catch (error) {
    logger.error('Database connection failed:', error);
    throw error;
  }
};

/**
 * Connect to the database
 * @returns {Promise<void>}
 */
export const connectDatabase = async (): Promise<void> => {
  try {
    await testConnection();

    // Run any pending migrations (optional)
    if (process.env.AUTO_MIGRATE === 'true') {
      logger.info('Running database migrations...');
      await db.migrate.latest();
      logger.info('Database migrations completed');
    }
  } catch (error) {
    logger.error('Failed to connect to the database:', error);
    throw error;
  }
};

/**
 * Close the database connection
 * @returns {Promise<void>}
 */
export const closeDatabase = async (): Promise<void> => {
  try {
    await db.destroy();
    logger.info('Database connection closed');
  } catch (error) {
    logger.error('Error closing database connection:', error);
    throw error;
  }
};

// Export the Knex instance for use in repositories
export default db;
