import { Inject, Injectable, Module, OnModuleDestroy } from '@nestjs/common';
import { Pool } from 'pg';
import { APP_ENVIRONMENT, AppEnvironment } from '../../../configuration/src';

export const POSTGRES_POOL = Symbol('POSTGRES_POOL');

export const postgresPoolProvider = {
  provide: POSTGRES_POOL,
  inject: [APP_ENVIRONMENT],
  useFactory: (env: AppEnvironment) =>
    new Pool({ connectionString: env.databaseUrl }),
};

@Injectable()
class PostgresLifecycle implements OnModuleDestroy {
  constructor(@Inject(POSTGRES_POOL) private readonly pool: Pool) {}

  async onModuleDestroy(): Promise<void> {
    await this.pool.end();
  }
}

@Module({
  providers: [postgresPoolProvider, PostgresLifecycle],
  exports: [postgresPoolProvider],
})
export class PostgresModule {}
