import { Test, TestingModule } from '@nestjs/testing';
import { DatabaseModule } from './DatabaseModule';

describe('DatabaseModule', () => {
  let module: TestingModule;

  beforeEach(async () => {
    // Clear environment variables to ensure consistent test behavior
    delete process.env.DATABASE_URL;
    delete process.env.DATABASE_HOST;
    delete process.env.DATABASE_PORT;
    delete process.env.DATABASE_USER;
    delete process.env.DATABASE_PASSWORD;
    delete process.env.DATABASE_NAME;
    delete process.env.NODE_ENV;

    module = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();
  });

  it('should compile the module', () => {
    expect(module).toBeDefined();
  });

  it('should configure TypeORM with DATABASE_URL when provided', async () => {
    process.env.DATABASE_URL = 'postgres://user:pass@localhost:5432/testdb';
    process.env.NODE_ENV = 'production';

    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });

  it('should configure TypeORM with individual connection parameters when DATABASE_URL is not provided', async () => {
    process.env.DATABASE_HOST = 'localhost';
    process.env.DATABASE_PORT = '5432';
    process.env.DATABASE_USER = 'testuser';
    process.env.DATABASE_PASSWORD = 'testpass';
    process.env.DATABASE_NAME = 'testdb';
    process.env.NODE_ENV = 'development';

    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });

  it('should use default values when connection parameters are not provided', async () => {
    process.env.NODE_ENV = 'test';

    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });

  it('should enable synchronization in non-production environments', async () => {
    process.env.NODE_ENV = 'development';

    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });

  it('should disable synchronization in production environment', async () => {
    process.env.NODE_ENV = 'production';

    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });

  it('should auto load entities', async () => {
    const testModule = await Test.createTestingModule({
      imports: [DatabaseModule],
    }).compile();

    expect(testModule).toBeDefined();
  });
});
