import { fork } from "node:child_process";
import type { TestProject } from "vitest/node";
import {
  show,
  listMachineUsers,
  getMachineUserToken,
  createWorkspace,
  deleteWorkspace,
  apply,
} from "@tailor-platform/sdk/cli";

declare module "vitest" {
  export interface ProvidedContext {
    url: string;
    token: string;
  }
}

const APP_NAME = "template-app";

export async function setup(project: TestProject) {
  const workspaceName = `${APP_NAME}-test-${Date.now()}`;
  const workspace = await createWorkspace({
    name: workspaceName,
    region: "asia-northeast",
  });

  const workspaceId = workspace.id;

  await apply({ workspaceId, yes: true });

  await new Promise<void>((resolve, reject) => {
    const child = fork("seed/exec.mjs", [], {
      env: { ...process.env, TAILOR_PLATFORM_WORKSPACE_ID: workspaceId },
      stdio: "inherit",
    });
    child.on("close", (code) =>
      code === 0 ? resolve() : reject(new Error(`seed exited with code ${code}`)),
    );
  });

  const app = await show({ workspaceId });
  const url = app.url;

  const machineUsers = await listMachineUsers({ workspaceId });
  const tokens = await getMachineUserToken({
    name: machineUsers[0].name,
    workspaceId,
  });
  const token = tokens.accessToken;

  project.provide("url", url);
  project.provide("token", token);

  return async () => {
    await deleteWorkspace({ workspaceId });
  };
}
