import 'reflect-metadata';

import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';

describe('Bootstrap seeding (HTTP, inmemory)', () => {
  const originalEnv = { ...process.env };

  let module: TestingModule | undefined;
  let app: import("@nestjs/common").INestApplication;

  beforeAll(async () => {
    vi.resetModules();

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

    const { AppModule } = await import('../../app.module');

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

    app = module.createNestApplication();
    await app.init();
  }, 20_000);

  afterAll(async () => {
    await app?.close();
    await module?.close();

    process.env = originalEnv;
    vi.restoreAllMocks();
  });

  it('exposes seeded leagues via HTTP (regression for repo instance mismatch)', async () => {
    const leaguesRes = await request(app.getHttpServer()).get('/leagues/total-leagues').expect(200);

    expect(leaguesRes.body).toBeDefined();
    expect(typeof leaguesRes.body.totalLeagues).toBe('number');
    expect(leaguesRes.body.totalLeagues).toBeGreaterThan(0);

    const racesRes = await request(app.getHttpServer()).get('/races/total-races').expect(200);

    expect(racesRes.body).toBeDefined();
    expect(typeof racesRes.body.totalRaces).toBe('number');
    expect(racesRes.body.totalRaces).toBeGreaterThan(0);
  });
});