import { Test } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

/**
 * Test setup utilities for PMC backend
 */

// Global test timeout
jest.setTimeout(30000);

// Mock database configuration for testing
export const testDatabaseConfig = {
  type: 'postgres' as const,
  host: process.env.TEST_DB_HOST || 'localhost',
  port: parseInt(process.env.TEST_DB_PORT, 10) || 5433,
  username: process.env.TEST_DB_USERNAME || 'postgres',
  password: process.env.TEST_DB_PASSWORD || 'postgres',
  database: process.env.TEST_DB_NAME || 'pmc_test',
  entities: [__dirname + '/../**/*.entity{.ts,.js}'],
  synchronize: true,
  dropSchema: true,
  logging: false,
};

/**
 * Create a testing module with TypeORM configured
 */
export const createTestingModule = async (imports: any[] = [], providers: any[] = []) => {
  return Test.createTestingModule({
    imports: [
      ConfigModule.forRoot({
        isGlobal: true,
        envFilePath: '.env.test',
      }),
      TypeOrmModule.forRoot(testDatabaseConfig),
      ...imports,
    ],
    providers,
  }).compile();
};

/**
 * Mock ConfigService for testing
 */
export const mockConfigService = {
  get: jest.fn((key: string, defaultValue?: any) => {
    const config = {
      'jwt.secret': 'test-secret',
      'jwt.expiresIn': '1h',
      'database.host': 'localhost',
      'database.port': 5433,
      'app.port': 3000,
    };
    return config[key] || defaultValue;
  }),
};

/**
 * Clear all mocks after each test
 */
afterEach(() => {
  jest.clearAllMocks();
});
