import { pool } from "@workspace/db";

async function tableExists(table: string): Promise<boolean> {
  const result = await pool.query(
    `SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1`,
    [table],
  );
  return (result.rowCount ?? 0) > 0;
}

async function main(): Promise<void> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    for (const table of [
      "message_reads",
      "messages",
      "conversation_participants",
      "conversations",
    ]) {
      if (await tableExists(table)) {
        await client.query(`DROP TABLE IF EXISTS "${table}" CASCADE`);
        console.log(`[remove-chat] Dropped table ${table}`);
      }
    }

    if (await tableExists("notifications")) {
      const r = await client.query(
        `DELETE FROM notifications
          WHERE related_type = 'conversation' OR type = 'chat'`,
      );
      if ((r.rowCount ?? 0) > 0) {
        console.log(
          `[remove-chat] Removed ${r.rowCount} chat-related notification row(s)`,
        );
      }
    }

    if (await tableExists("apps")) {
      const idRes = await client.query(
        `SELECT id FROM apps WHERE slug = 'chat'`,
      );
      const chatAppId = idRes.rows[0]?.id as number | undefined;
      if (chatAppId !== undefined) {
        for (const link of [
          "user_app_orders",
          "app_opens",
          "app_permissions",
          "group_apps",
        ]) {
          if (await tableExists(link)) {
            await client.query(`DELETE FROM "${link}" WHERE app_id = $1`, [
              chatAppId,
            ]);
          }
        }
        await client.query(`DELETE FROM apps WHERE id = $1`, [chatAppId]);
        console.log(
          `[remove-chat] Removed chat app (id=${chatAppId}) and link rows`,
        );
      }
    }

    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

main()
  .then(() => pool.end())
  .catch(async (err) => {
    console.error("[remove-chat] failed:", err);
    await pool.end();
    process.exit(1);
  });
