import { expect } from "@playwright/test";
import { apiRequest } from "./api.js";
import { expectId, readJsonSafe } from "./generalFixtures.js";
function buildMinimalDefinitionPayload(timestamp, suffix = "") {
  const id = `qa-wf${suffix}-${timestamp}`;
  return {
    workflowId: id,
    workflowName: `QA Workflow${suffix} ${timestamp}`,
    description: `Integration test definition ${id}`,
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        {
          transitionId: "start-to-end",
          fromStepId: "start",
          toStepId: "end",
          trigger: "auto"
        }
      ]
    },
    enabled: true
  };
}
function buildUserTaskDefinitionPayload(timestamp) {
  return {
    workflowId: `qa-wf-task-${timestamp}`,
    workflowName: `QA User Task Workflow ${timestamp}`,
    description: "Workflow with a USER_TASK step for integration testing",
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        {
          stepId: "review",
          stepName: "Review",
          stepType: "USER_TASK",
          userTaskConfig: {
            assignedTo: "admin",
            formSchema: {
              fields: [
                { name: "approved", type: "boolean", required: true },
                { name: "comments", type: "string" }
              ]
            }
          }
        },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        {
          transitionId: "start-to-review",
          fromStepId: "start",
          toStepId: "review",
          trigger: "auto"
        },
        {
          transitionId: "review-to-end",
          fromStepId: "review",
          toStepId: "end",
          trigger: "manual"
        }
      ]
    },
    enabled: true
  };
}
async function createWorkflowDefinitionFixture(request, token, data) {
  const response = await apiRequest(request, "POST", "/api/workflows/definitions", { token, data });
  const body = await readJsonSafe(response);
  expect(response.status(), `POST /api/workflows/definitions should return 201 (got ${response.status()}: ${JSON.stringify(body)})`).toBe(201);
  return expectId(body?.data?.id, "Definition creation response should include data.id");
}
async function deleteWorkflowDefinitionIfExists(request, token, definitionId) {
  if (!token || !definitionId) return;
  await apiRequest(
    request,
    "DELETE",
    `/api/workflows/definitions/${encodeURIComponent(definitionId)}`,
    { token }
  ).catch(() => void 0);
}
async function startWorkflowInstanceFixture(request, token, data) {
  const response = await apiRequest(request, "POST", "/api/workflows/instances", { token, data });
  const body = await readJsonSafe(response);
  expect(response.status(), `POST /api/workflows/instances should return 201 (got ${response.status()}: ${JSON.stringify(body)})`).toBe(201);
  return expectId(body?.data?.instance?.id, "Instance start response should include data.instance.id");
}
async function cancelWorkflowInstanceIfExists(request, token, instanceId) {
  if (!token || !instanceId) return;
  await apiRequest(
    request,
    "POST",
    `/api/workflows/instances/${encodeURIComponent(instanceId)}/cancel`,
    { token }
  ).catch(() => void 0);
}
function buildClaimableUserTaskDefinitionPayload(timestamp, suffix = "") {
  const id = `qa-wf-claim${suffix}-${timestamp}`;
  return {
    workflowId: id,
    workflowName: `QA Claimable User Task${suffix} ${timestamp}`,
    description: `Integration test definition ${id}`,
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        {
          stepId: "review",
          stepName: "Review",
          stepType: "USER_TASK",
          userTaskConfig: {
            assignedTo: ["admin"],
            formSchema: {
              properties: {
                approved: { type: "boolean" },
                comments: { type: "string" }
              },
              required: ["approved"]
            }
          }
        },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        { transitionId: "start-to-review", fromStepId: "start", toStepId: "review", trigger: "auto" },
        { transitionId: "review-to-end", fromStepId: "review", toStepId: "end", trigger: "auto" }
      ]
    },
    enabled: true
  };
}
function buildAssignedUserTaskDefinitionPayload(timestamp, assignedUserId, suffix = "") {
  const id = `qa-wf-assigned${suffix}-${timestamp}`;
  return {
    workflowId: id,
    workflowName: `QA Assigned User Task${suffix} ${timestamp}`,
    description: `Integration test definition ${id}`,
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        {
          stepId: "review",
          stepName: "Review",
          stepType: "USER_TASK",
          userTaskConfig: {
            assignedTo: assignedUserId,
            formSchema: { properties: { approved: { type: "boolean" } } }
          }
        },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        { transitionId: "start-to-review", fromStepId: "start", toStepId: "review", trigger: "auto" },
        { transitionId: "review-to-end", fromStepId: "review", toStepId: "end", trigger: "auto" }
      ]
    },
    enabled: true
  };
}
function buildSignalDefinitionPayload(timestamp, signalName = "approval", suffix = "") {
  const id = `qa-wf-signal${suffix}-${timestamp}`;
  return {
    workflowId: id,
    workflowName: `QA Signal Workflow${suffix} ${timestamp}`,
    description: `Integration test definition ${id}`,
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        { stepId: "wait", stepName: "Wait For Signal", stepType: "WAIT_FOR_SIGNAL", signalConfig: { signalName } },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        { transitionId: "start-to-wait", fromStepId: "start", toStepId: "wait", trigger: "auto" },
        { transitionId: "wait-to-end", fromStepId: "wait", toStepId: "end", trigger: "auto" }
      ]
    },
    enabled: true
  };
}
function buildManualAdvanceDefinitionPayload(timestamp, suffix = "") {
  const id = `qa-wf-advance${suffix}-${timestamp}`;
  return {
    workflowId: id,
    workflowName: `QA Manual Advance Workflow${suffix} ${timestamp}`,
    description: `Integration test definition ${id}`,
    version: 1,
    definition: {
      steps: [
        { stepId: "start", stepName: "Start", stepType: "START" },
        { stepId: "mid", stepName: "Middle", stepType: "AUTOMATED" },
        { stepId: "end", stepName: "End", stepType: "END" }
      ],
      transitions: [
        { transitionId: "start-to-mid", fromStepId: "start", toStepId: "mid", trigger: "manual" },
        { transitionId: "mid-to-end", fromStepId: "mid", toStepId: "end", trigger: "manual" }
      ]
    },
    enabled: true
  };
}
async function getWorkflowInstanceSnapshot(request, token, instanceId) {
  const response = await apiRequest(
    request,
    "GET",
    `/api/workflows/instances/${encodeURIComponent(instanceId)}`,
    { token }
  );
  if (response.status() !== 200) return null;
  const body = await readJsonSafe(response);
  return body?.data ?? null;
}
async function pollWorkflowInstance(request, token, instanceId, predicate, options = {}) {
  const timeoutMs = options.timeoutMs ?? 8e3;
  const intervalMs = options.intervalMs ?? 250;
  const deadline = Date.now() + timeoutMs;
  let last = null;
  for (; ; ) {
    last = await getWorkflowInstanceSnapshot(request, token, instanceId);
    if (last && predicate(last)) return last;
    if (Date.now() >= deadline) return last;
    await new Promise((resolve) => setTimeout(resolve, intervalMs));
  }
}
async function listWorkflowInstanceTasks(request, token, instanceId) {
  const response = await apiRequest(
    request,
    "GET",
    `/api/workflows/tasks?workflowInstanceId=${encodeURIComponent(instanceId)}`,
    { token }
  );
  if (response.status() !== 200) return [];
  const body = await readJsonSafe(response);
  return body?.data ?? [];
}
async function findInstanceUserTask(request, token, instanceId, options = {}) {
  const timeoutMs = options.timeoutMs ?? 8e3;
  const intervalMs = options.intervalMs ?? 250;
  const statuses = options.statuses ?? ["PENDING", "IN_PROGRESS"];
  const deadline = Date.now() + timeoutMs;
  for (; ; ) {
    const tasks = await listWorkflowInstanceTasks(request, token, instanceId);
    const match = tasks.find((task) => typeof task.status === "string" && statuses.includes(task.status));
    if (match?.id) return match;
    if (Date.now() >= deadline) return null;
    await new Promise((resolve) => setTimeout(resolve, intervalMs));
  }
}
export {
  buildAssignedUserTaskDefinitionPayload,
  buildClaimableUserTaskDefinitionPayload,
  buildManualAdvanceDefinitionPayload,
  buildMinimalDefinitionPayload,
  buildSignalDefinitionPayload,
  buildUserTaskDefinitionPayload,
  cancelWorkflowInstanceIfExists,
  createWorkflowDefinitionFixture,
  deleteWorkflowDefinitionIfExists,
  findInstanceUserTask,
  getWorkflowInstanceSnapshot,
  listWorkflowInstanceTasks,
  pollWorkflowInstance,
  startWorkflowInstanceFixture
};
//# sourceMappingURL=workflowsFixtures.js.map
