import type { PrismaClient } from '@shieldai/db';

let prisma: PrismaClient | null = null;

export async function initializeTestDB(): Promise<PrismaClient> {
  if (!prisma) {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    process.env.DATABASE_URL = process.env.DATABASE_URL || 'postgresql://test:test@localhost:5432/test';
    const db = await import('@shieldai/db');
    const PC = (db as unknown as { PrismaClient: new () => PrismaClient }).PrismaClient;
    prisma = new PC();
  }
  return prisma;
}

export async function cleanupTestDB(): Promise<void> {
  if (prisma) {
    await prisma.$disconnect();
    prisma = null;
  }
}

export function getTestDB(): PrismaClient {
  if (!prisma) {
    throw new Error('Test database not initialized. Call initializeTestDB() first.');
  }
  return prisma;
}
