import 'reflect-metadata';

import { MODULE_METADATA } from '@nestjs/common/constants';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { LEAGUE_REPOSITORY_TOKEN } from '../inmemory/InMemoryRacingPersistenceModule';

describe('RacingPersistenceModule', () => {
  const originalEnv = { ...process.env };

  afterEach(() => {
    process.env = originalEnv;
    vi.restoreAllMocks();
  });

  it('uses inmemory providers when GRIDPILOT_API_PERSISTENCE=inmemory', async () => {
    vi.resetModules();

    process.env.GRIDPILOT_API_PERSISTENCE = 'inmemory';
    delete process.env.DATABASE_URL;

    const { RacingPersistenceModule } = await import('./RacingPersistenceModule');
    const { InMemoryLeagueRepository } = await import('@adapters/racing/persistence/inmemory/InMemoryLeagueRepository');

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

    const leagueRepo = module.get(LEAGUE_REPOSITORY_TOKEN);
    expect(leagueRepo).toBeInstanceOf(InMemoryLeagueRepository);

    await module.close();
  });

  it('uses postgres module when GRIDPILOT_API_PERSISTENCE=postgres', async () => {
    vi.resetModules();

    process.env.GRIDPILOT_API_PERSISTENCE = 'postgres';
    delete process.env.DATABASE_URL;

    const { RacingPersistenceModule } = await import('./RacingPersistenceModule');
    const { PostgresRacingPersistenceModule } = await import('../postgres/PostgresRacingPersistenceModule');

    const imports = Reflect.getMetadata(MODULE_METADATA.IMPORTS, RacingPersistenceModule) as unknown[];
    expect(imports).toContain(PostgresRacingPersistenceModule);
  });
});