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 { PAYMENTS_WALLET_REPOSITORY_TOKEN } from './PaymentsPersistenceTokens';

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

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

    const walletRepo = module.get(PAYMENTS_WALLET_REPOSITORY_TOKEN);
    expect(walletRepo).toBeInstanceOf(InMemoryWalletRepository);

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

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