import { showHUD } from "@raycast/api";
import { runYabaiCommand } from "./helpers/scripts";
import { showFailureToast } from "@raycast/utils";

export default async function Command() {
  try {
    const { stdout: spaceOutput } = await runYabaiCommand(`-m query --spaces --space mouse`);
    const currentSpace = JSON.parse(spaceOutput);
    let moveFocusIndex = currentSpace.index - 1;
    
    if (currentSpace.index === 0) {
      moveFocusIndex = currentSpace.index + 1;
    }
    
    const { stderr: stderr3 } = await runYabaiCommand(`-m space --focus ${moveFocusIndex}`);
    if (stderr3) {
      console.log(stderr3);
      throw new Error(stderr3);
    }
    
    const { stderr } = await runYabaiCommand(`-m space --destroy ${currentSpace.index}`);

    if (stderr) {
      throw new Error(stderr);
    }

    await showHUD(`Destroyed Space`);
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes("Yabai executable not found")) {
        return;
      }

      showFailureToast(error, {
        title: "Failed to destroy space",
      });
    } else {
      showFailureToast(error, {
        title: "Failed to destroy space",
      });
    }
  }
}
