import { Kysely, PostgresDialect } from 'kysely';
import { Pool } from 'pg';
import { ConfigService } from '@nestjs/config';
import { AppConfig } from '@/config/configs';
import { DB } from './database.type'; // generate type from kysely-codegen command

// Raw PostgreSQL Connection Pool Provider
export const pgPoolProvider = {
  provide: Pool,
  inject: [ConfigService],
  useFactory: (configService: ConfigService<AppConfig, true>) => {
    const { host, port, username, password, name } = configService.get('database', { infer: true });
    return new Pool({
      host,
      port,
      user: username,
      password,
      database: name,
      max: 20,
      connectionTimeoutMillis: 3000,
    });
  },
};

// Kysely Query Builder Provider (shares the same PG Pool)
export const kyselyProvider = {
  provide: Kysely,
  inject: [Pool],
  useFactory: (pool: Pool) => {
    return new Kysely<DB>({
      dialect: new PostgresDialect({
        pool,
      }),
    });
  },
};
