import 'reflect-metadata';

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

import { USER_REPOSITORY_TOKEN } from './IdentityPersistenceTokens';

describe('IdentityPersistenceModule', () => {
  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 { IdentityPersistenceModule } = await import('./IdentityPersistenceModule');
    const { InMemoryUserRepository } = await import('@adapters/identity/persistence/inmemory/InMemoryUserRepository');

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

    const userRepo = module.get(USER_REPOSITORY_TOKEN);
    expect(userRepo).toBeInstanceOf(InMemoryUserRepository);

    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 { IdentityPersistenceModule } = await import('./IdentityPersistenceModule');
    const { PostgresIdentityPersistenceModule } = await import('../postgres/PostgresIdentityPersistenceModule');

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