import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { deleteWorkspace } from "@tailor-platform/sdk/cli";
import type { E2eState } from "./global-setup";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const STATE_FILE = path.resolve(__dirname, ".e2e-state.json");

async function globalTeardown() {
  if (!fs.existsSync(STATE_FILE)) {
    return;
  }

  const state = JSON.parse(fs.readFileSync(STATE_FILE, "utf-8")) as E2eState;

  // Only delete a workspace this run created. A CI-provided workspace is
  // shared by other jobs, so leave it.
  if (state.ownsWorkspace) {
    await deleteWorkspace({ workspaceId: state.workspaceId });
  }

  fs.unlinkSync(STATE_FILE);
}

export default globalTeardown;
