import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { ClsService } from 'nestjs-cls';
import pkg from 'pg';
import { Logger } from 'winston';
import * as schema from './schema';
import { PG_CONNECTION } from './schema';
const { Pool } = pkg;
@Module({
  imports: [ConfigModule],
  providers: [
    {
      provide: PG_CONNECTION,
      inject: [ConfigService, WINSTON_MODULE_PROVIDER, ClsService],
      useFactory: async (configService: ConfigService, logger: Logger, cls: ClsService) => {
        const connectionString = configService.get<string>('DATABASE_URL');
        // const dbHost = configService.get<string>('DB_HOST');
        // const dbPort = configService.get<string>('DB_PORT');
        // const dbName = configService.get<string>('DB_NAME');
        // const dbUser = configService.get<string>('DB_USER');
        const dbPassword = configService.get<string>('DB_PASSWORD');
        // logger.info(`Drizzle Connection - URL: ${connectionString}, Host: ${dbHost}, Port: ${dbPort}, DB: ${dbName}, User: ${dbUser}`);
        // console.log(`---> Drizzle Connection - URL: ${connectionString}, Host: ${dbHost}, Port: ${dbPort}, DB: ${dbName}, User: ${dbUser}`);
        const pool = new Pool({
          connectionString,
          // ssl: true, // Falls benötigt
        });

        // Definiere einen benutzerdefinierten Logger für Drizzle
        const drizzleLogger = {
          logQuery(query: string, params: unknown[]): void {
            const ip = cls.get('ip') || 'unknown';
            const countryCode = cls.get('countryCode') || 'unknown';
            const username = cls.get('username') || 'unknown';
            logger.info(`IP: ${ip} (${countryCode}) (${username}) - Query: ${query} - Params: ${JSON.stringify(params)}`);
          },
        };

        return drizzle(pool, { schema, logger: drizzleLogger });
      },
    },
  ],
  exports: [PG_CONNECTION],
})
export class DrizzleModule {}
