/**
 * Empties every application table, then leaves the database ready for the seed.
 * Schema and migration history are untouched — no DROP/CREATE privilege needed,
 * so this also works on a shared host where `prisma migrate reset` cannot run.
 *
 * Run: cd apps/api && npm run db:reset      (truncate + seed)
 *      cd apps/api && npm run db:truncate   (truncate only)
 */
import { PrismaClient } from '@prisma/client';

// Prisma's migration bookkeeping. Wiping it would make `migrate deploy` try to
// re-apply every migration against a schema that already has them.
const KEEP = ['_prisma_migrations'];

/** Host + database name of a connection string, for the "about to wipe X" line. */
function describe(url: string): string {
  try {
    const u = new URL(url);
    return `${u.hostname}:${u.port || '3306'}/${u.pathname.replace(/^\//, '')}`;
  } catch {
    return '(unparseable DATABASE_URL)';
  }
}

async function main(): Promise<void> {
  const url = process.env.DATABASE_URL;
  if (!url) throw new Error('DATABASE_URL is not set');

  if (process.env.NODE_ENV === 'production' && process.env.ALLOW_PRODUCTION_RESET !== '1') {
    throw new Error('Refusing to wipe a production database. Set ALLOW_PRODUCTION_RESET=1 if you really mean it.');
  }

  // FOREIGN_KEY_CHECKS is a *session* variable, so every TRUNCATE has to run on
  // the same connection that disabled it. Pinning the pool to one connection is
  // what guarantees that.
  const pinned = url + (url.includes('?') ? '&' : '?') + 'connection_limit=1';
  const prisma = new PrismaClient({ datasourceUrl: pinned });

  console.log(`Wiping ${describe(url)} …`);
  try {
    const rows = await prisma.$queryRawUnsafe<{ TABLE_NAME: string }[]>(
      "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'",
    );
    const tables = rows.map((r) => r.TABLE_NAME).filter((t) => !KEEP.includes(t)).sort();
    if (tables.length === 0) {
      console.log('  nothing to wipe (no tables found — run `npm run prisma:deploy` first)');
      return;
    }

    await prisma.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 0');
    try {
      for (const t of tables) await prisma.$executeRawUnsafe(`TRUNCATE TABLE \`${t}\``);
    } finally {
      await prisma.$executeRawUnsafe('SET FOREIGN_KEY_CHECKS = 1');
    }
    console.log(`  ${tables.length} table(s) emptied, ${KEEP.length} kept (${KEEP.join(', ')})`);
  } finally {
    await prisma.$disconnect();
  }
}

main().catch((e) => {
  console.error(e instanceof Error ? e.message : e);
  process.exit(1);
});
