import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

beforeAll(async () => {
  // Database connection check
  try {
    await prisma.$connect();
    console.log('Database connected for integration tests');
  } catch (error) {
    console.warn('Database not available for integration tests, some tests may be skipped');
  }
});

afterAll(async () => {
  await prisma.$disconnect();
});

// Global test utilities
global.testUtils = {
  prisma,
  cleanDatabase: async () => {
    const tablenames = await prisma.$queryRaw<
      Array<{ tablename: string }>
    >`SELECT tablename FROM pg_tables WHERE schemaname='public'`;

    for (const { tablename } of tablenames) {
      if (tablename !== '_prisma_migrations') {
        try {
          await prisma.$executeRawUnsafe(`TRUNCATE TABLE "public"."${tablename}" CASCADE;`);
        } catch (error) {
          console.log(`Could not truncate table ${tablename}`);
        }
      }
    }
  },
};

declare global {
  var testUtils: {
    prisma: PrismaClient;
    cleanDatabase: () => Promise<void>;
  };
}
