import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';

export const getDatabaseConfig = (
  configService: ConfigService,
): TypeOrmModuleOptions => {
  const sslEnabled = configService.get<string>('DATABASE_SSL', 'false') === 'true';

  return {
    type: 'postgres',
    host: configService.get<string>('DATABASE_HOST', 'localhost'),
    port: configService.get<number>('DATABASE_PORT', 5555),
    username: configService.get<string>('DATABASE_USER', 'maternal_user'),
    password: configService.get<string>('DATABASE_PASSWORD'),
    database: configService.get<string>('DATABASE_NAME', 'maternal_app'),
    entities: [__dirname + '/../**/*.entity{.ts,.js}'],
    migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
    synchronize: false, // Always use migrations in production
    logging: configService.get<string>('NODE_ENV') === 'development',
    ssl: sslEnabled ? { rejectUnauthorized: false } : false,
    extra: {
      max: 20, // Maximum number of clients in the pool
      min: 2, // Minimum number of clients in the pool
      idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
      connectionTimeoutMillis: 10000, // Return an error if connection takes longer than 10 seconds
    },
    retryAttempts: 10,
    retryDelay: 3000,
    autoLoadEntities: true,
  };
};
