import "dotenv/config";
import mysql from "mysql2/promise";
import type { RowDataPacket } from "mysql2";

const escapeIdentifier = (value: string) => `\`${value.replace(/`/g, "``")}\``;

const run = async () => {
  if (process.env.ALLOW_DB_RESET !== "true") {
    console.error(
      "Refusing to reset database. Set ALLOW_DB_RESET=true to confirm this destructive action.",
    );
    process.exit(1);
  }

  if (!process.env.DATABASE_URL) {
    console.error("DATABASE_URL is required.");
    process.exit(1);
  }

  const connection = await mysql.createConnection(process.env.DATABASE_URL);

  const [databaseRows] = await connection.query<
    Array<RowDataPacket & { databaseName: string | null }>
  >("select database() as databaseName");
  const databaseName = databaseRows[0]?.databaseName;

  if (!databaseName) {
    await connection.end();
    throw new Error("Could not determine active database from DATABASE_URL.");
  }

  const [tableRows] = await connection.query<
    Array<RowDataPacket & { tableName: string }>
  >(
    "select table_name as tableName from information_schema.tables where table_schema = database() and table_type = 'BASE TABLE'",
  );

  console.log(
    `Resetting database '${databaseName}' (${tableRows.length} tables)...`,
  );

  await connection.query("set foreign_key_checks = 0");
  for (const row of tableRows) {
    await connection.query(
      `drop table if exists ${escapeIdentifier(row.tableName)}`,
    );
    console.log(`Dropped table: ${row.tableName}`);
  }
  await connection.query("set foreign_key_checks = 1");

  await connection.end();
  console.log("Database reset complete. Run migrations and seed next.");
  process.exit(0);
};

run().catch((err) => {
  console.error("Database reset failed:", err);
  process.exit(1);
});
