import { Prisma, PrismaClient } from '@prisma/client';
import { seed } from './seed';
import { assertTestDatabaseUrl, loadTestEnv } from './test-env';

/**
 * Remet la base de TEST dans un état connu : truncate de toutes les tables du
 * schéma Prisma puis re-seed (admin + super_admin).
 * Réf : docs/e2e-testing-spec.md §4.3
 */
export async function resetDb(prisma: PrismaClient): Promise<void> {
  assertTestDatabaseUrl();

  const tables = Prisma.dmmf.datamodel.models.map(
    (model) => model.dbName ?? model.name,
  );

  await prisma.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 0');
  try {
    for (const table of tables) {
      await prisma.$executeRawUnsafe(`TRUNCATE TABLE \`${table}\``);
    }
  } finally {
    await prisma.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 1');
  }

  await seed(prisma);
}

if (require.main === module) {
  loadTestEnv();
  const prisma = new PrismaClient();
  resetDb(prisma)
    .then(() => {
      console.log('Reset OK : tables tronquées + re-seed.');
    })
    .catch((error) => {
      console.error(error);
      process.exitCode = 1;
    })
    .finally(() => prisma.$disconnect());
}
