import { defineConfig, PostgreSqlDriver } from '@mikro-orm/postgresql';
import * as dotenv from 'dotenv';

// 1. Load environment variables from your .env file
dotenv.config();

// 2. Read variables directly from process.env
const DB_PASS = process.env.DB_PASS;
const DB_USER = process.env.DB_USER;
const DB_HOST = process.env.DB_HOST;
const DB_PORT = process.env.DB_PORT ? +process.env.DB_PORT : 5432;
const DB_NAME = process.env.DB_NAME;
const isProduction = process.env.NODE_ENV === 'production';

// 3. Add checks to ensure variables are loaded
if (!DB_PASS || !DB_USER || !DB_HOST || !DB_PORT || !DB_NAME) {
  throw new Error('One or more database environment variables are not set.');
}

const encodedPassword = encodeURIComponent(DB_PASS);

// 4. Export the result of defineConfig as the default
export default defineConfig({
  entities: ['dist/**/*.entity.js'],
  entitiesTs: ['src/**/*.entity.ts'],
  driver: PostgreSqlDriver,
  dbName: DB_NAME,
  debug: false,
  clientUrl: `postgres://${DB_USER}:${encodedPassword}@${DB_HOST}:${DB_PORT}`,
  ensureDatabase: isProduction
    ? false
    : {
        forceCheck: true,
        create: true,
        schema: 'update',
      },
  forceUtcTimezone: true,
  pool: {
    min: isProduction ? 5 : 2,
    max: isProduction ? 20 : 10,
    idleTimeoutMillis: 30000,
    acquireTimeoutMillis: 30000,
    reapIntervalMillis: 1000,
    createTimeoutMillis: 15000,
    destroyTimeoutMillis: 5000,
  },
  // 5. Use console for CLI logging, not the injected Nest logger
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  logger: isProduction ? console.log.bind(console) : console.debug.bind(console),
  schemaGenerator: {
    disableForeignKeys: false,
  },
  migrations: {
    path: './database/migrations',
    pathTs: './database/migrations',
    tableName: 'migrations',
    transactional: true,
    allOrNothing: true,
    dropTables: false,
    safe: true,
    emit: 'ts',
  },
  connect: true,
  // CLI-only (migrations/seeders run outside HTTP); runtime app config must not set this.
  allowGlobalContext: true,
  seeder: {
    path: './dist/seeders',
    pathTs: './src/seeders',
    defaultSeeder: 'DatabaseSeeder',
  },
  driverOptions: {
    connection: {
      keepAlive: true,
      keepAliveInitialDelayMillis: 10000,
      statement_timeout: 60000,
      query_timeout: 60000,
      idle_in_transaction_session_timeout: 60000,
      connectionTimeoutMillis: 10000,
      application_name: DB_NAME,
    },
    connectionRetries: 5,
    connectionRetryDelay: 3000,
    validateConnection: (connection: any) => {
      try {
        return !!(connection && !connection.closed);
      } catch (e: unknown) {
        // Use console.error directly
        console.error(`Connection validation failed: ${(e as Error).message}`);
        return false;
      }
    },
    poolErrorHandler: (err: Error) => {
      // Use console.error directly
      console.error(`PostgreSQL pool error: ${err.message}`);
      if (err.message.includes('ECONNRESET') || err.message.includes('Connection terminated unexpectedly')) {
        console.warn('Connection reset detected, will attempt to reconnect');
        return true;
      }
      return false;
    },
  },
});
