import { DataSource } from 'typeorm';
import 'dotenv/config';

/**
 * TypeORM DataSource configuration for PostgreSQL database connection
 *
 * This configuration establishes the connection to the PostgreSQL database
 * using environment variables for flexibility across different environments
 * (development, staging, production).
 *
 * Features:
 * - Environment variable based configuration
 * - UTC timezone for consistent timestamp handling
 * - Migration support with versioned migrations table
 * - Entity auto-discovery
 *
 * @example
 * // Usage in TypeORM CLI or application bootstrap
 * await connectionSource.initialize();
 * // or use in NestJS TypeORM module configuration
 */
export const connectionSource = new DataSource({
  /**
   * Database type (PostgreSQL)
   */
  type: 'postgres',

  /**
   * Connection configuration from environment variables
   */
  host: process.env.POSTGRES_HOST, // Database hostname/IP
  port: +(process.env.POSTGRES_PORT || 5432), // Database port (default: 5432)
  username: process.env.POSTGRES_USER, // Database username
  password: process.env.POSTGRES_PASSWORD, // Database password
  database: process.env.POSTGRES_DATABASE, // Database name

  /**
   * Logging and synchronization settings
   *
   * @note synchronize: false in production to prevent accidental schema changes
   * @note logging: false in production for better performance
   */
  logging: false, // Disable query logging (enable for debugging)
  synchronize: false, // Never auto-sync in production - use migrations

  /**
   * Connection name for multiple database connections
   */
  name: 'default', // Default connection name

  /**
   * Extra connection options
   */
  extra: {
    timezone: 'UTC', // Ensure consistent UTC timezone for all timestamps
    // Additional options could include:
    // connectionTimeoutMillis: 5000, // Connection timeout
    // max: 20,                      // Maximum connection pool size
  },

  /**
   * Entity and migration configuration
   */
  entities: ['src/entities/*.entity{.ts,.js}'], // Entity file pattern
  migrations: ['src/migrations_v2/**/*.migration{.ts,.js}'], // Migration file pattern
  migrationsTableName: 'migrations_v2', // Custom migrations table name
  migrationsRun: false, // Don't auto-run migrations on startup

  /**
   * Additional configuration options to consider:
   *
   * ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
   * cache: true,                                      // Enable query caching
   * entitySkipConstructor: true,                      // Skip entity constructors for performance
   */
});

/**
 * Initialize the database connection immediately
 *
 * This initialization runs when the module is imported, which may be
 * appropriate for CLI usage but consider lazy initialization for applications.
 *
 * @note For NestJS applications, consider initializing in AppModule instead
 */
connectionSource
  .initialize()
  .then(() => {
    console.log('Data Source has been initialized!');
  })
  .catch((err) => {
    console.error('Error during Data Source initialization', err);
  });
