import type { INestApplication } from '@nestjs/common';
import { PrismaService } from '../../../src/prisma.service.js';
import { loginAllRoles, type E2EAccessTokenMap } from './e2e-auth.helper.js';
import { createE2eApp } from './e2e-app.helper.js';
import {
  ensureE2EFixtures,
  type E2ESeedFixtures,
} from './e2e-fixtures.helper.js';

export interface E2EContext {
  app: INestApplication;
  prisma: PrismaService;
  tokens: E2EAccessTokenMap;
  fixtures: E2ESeedFixtures;
}

export async function createE2EContext(): Promise<E2EContext> {
  const app = await createE2eApp();
  const prisma = app.get(PrismaService);
  const fixtures = await ensureE2EFixtures(app, prisma);
  const tokens = await loginAllRoles(app, fixtures);

  return {
    app,
    prisma,
    fixtures,
    tokens,
  };
}

export async function closeE2EContext(ctx?: E2EContext) {
  if (!ctx) {
    return;
  }

  await ctx.prisma.$disconnect();
  await ctx.app.close();
}
