import Surreal from "surrealdb";

const DB_URL = "wss://gentle-island-06di2pv2c9po3a8euttd1alkek.aws-euw1.surreal.cloud";
const DB_USER = process.env.SURREAL_USER || "rootuser";
const DB_PASS = process.env.SURREAL_PASS || "n1n@S1mone";

async function addHasAudioField() {
  const db = new Surreal();

  try {
    await db.connect(DB_URL, {
      namespace: "neoad",
      database: "neodb"
    });
    await db.signin({ username: DB_USER, password: DB_PASS });

    console.log("Connected to database");

    // First, check current screens
    const screens = await db.query<[any[]]>(`
      SELECT id, name, has_audio FROM screen LIMIT 5
    `);
    console.log("\nCurrent screens (sample):");
    console.log(screens[0] || []);

    // Try updating a single screen first with MERGE
    const mergeResult = await db.query<[any]>(`
      UPDATE screen:es_381 MERGE { has_audio: false } RETURN AFTER;
    `);
    console.log("\nMerge result:", JSON.stringify(mergeResult[0], null, 2));

    // Add has_audio = false to all screens
    const result = await db.query<[any[]]>(`
      UPDATE screen MERGE { has_audio: false } RETURN AFTER;
    `);
    console.log(`\nUpdated ${result[0]?.length || 0} screens with has_audio = false`);
    if (result[0]?.length > 0) {
      console.log("First updated screen:", JSON.stringify(result[0][0], null, 2));
    }

    // Small delay before verification
    await new Promise(resolve => setTimeout(resolve, 500));

    // Verify with explicit field check - select all fields
    const verification = await db.query<[any[]]>(`
      SELECT * FROM screen:es_381
    `);
    console.log("\nSingle screen after update:", JSON.stringify(verification[0]?.[0], null, 2));

  } catch (error) {
    console.error("Error:", error);
  } finally {
    await db.close();
  }
}

addHasAudioField();
