import { beforeEach, describe, expect, test, vi } from "vitest";
import { WorkflowConflictError, WorkflowInvalidInputError } from "../errors";
import type {
  WorkflowRowWithLastRun,
  WorkflowRunListRow,
  WorkflowRunRow,
  WorkflowRunWithLogsRow,
  WorkflowsLogger,
} from "../services/ports";
import type { WorkflowsService } from "../services/workflows.service";
import type { TWorkflowTriggerRunPayload } from "../types/runs";
import type { AuthorizedWorkspace, WorkflowApiContext } from "./context";
import { createWorkflowsHandlers } from "./workflows.handlers";

const surveyId = "cm9zr4q7i000108l84gozfggr";
const workspaceId = "cm9zr4mps000008l8btfy1vtz";
const workflowId = "cm9zr4t2b000208l8h2m1aq3c";
const responseId = "cm9zr4rsp000708l8bqccpfrx";

const definition = {
  schemaVersion: 1 as const,
  trigger: {
    id: "trigger",
    type: "trigger" as const,
    triggerType: "response.completed" as const,
    config: { surveyId, endingCardIds: [] },
  },
  nodes: [
    {
      id: "send-email",
      type: "action" as const,
      actionType: "send_email" as const,
      config: {
        from: "noreply@example.com",
        to: "support@example.com",
        replyTo: ["support@example.com"],
        subject: "Thanks",
        body: "Thanks for your response.",
        attachResponseData: true,
      },
    },
  ],
  edges: [{ id: "e1", source: "trigger", target: "send-email" }],
  entryNodeId: "trigger",
};

const makeRow = (overrides: Partial<WorkflowRowWithLastRun> = {}): WorkflowRowWithLastRun => ({
  id: workflowId,
  createdAt: new Date("2026-06-11T09:30:00.000Z"),
  updatedAt: new Date("2026-06-12T09:30:00.000Z"),
  name: "Notify team",
  description: null,
  status: "draft",
  workspaceId,
  createdBy: null,
  creator: null,
  definition,
  runs: [],
  _count: { runs: 0 },
  ...overrides,
});

const service = {
  listWorkflows: vi.fn<WorkflowsService["listWorkflows"]>(),
  createWorkflow: vi.fn<WorkflowsService["createWorkflow"]>(),
  getWorkflowById: vi.fn<WorkflowsService["getWorkflowById"]>(),
  updateWorkflow: vi.fn<WorkflowsService["updateWorkflow"]>(),
  duplicateWorkflow: vi.fn<WorkflowsService["duplicateWorkflow"]>(),
  deleteWorkflow: vi.fn<WorkflowsService["deleteWorkflow"]>(),
  setStatus: vi.fn<WorkflowsService["setStatus"]>(),
  enableWorkflow: vi.fn<WorkflowsService["enableWorkflow"]>(),
  disableWorkflow: vi.fn<WorkflowsService["disableWorkflow"]>(),
  listWorkflowRuns: vi.fn<WorkflowsService["listWorkflowRuns"]>(),
  getWorkflowRun: vi.fn<WorkflowsService["getWorkflowRun"]>(),
  regenerateWebhookToken: vi.fn<WorkflowsService["regenerateWebhookToken"]>(),
  revealWebhookToken: vi.fn<WorkflowsService["revealWebhookToken"]>(),
  getTriggerSample: vi.fn<WorkflowsService["getTriggerSample"]>(),
  getLastCall: vi.fn<WorkflowsService["getLastCall"]>(),
  setTriggerSample: vi.fn<WorkflowsService["setTriggerSample"]>(),
  createTestRun: vi.fn<WorkflowsService["createTestRun"]>(),
};
const handlers = createWorkflowsHandlers(service);

const readJson = async <T>(res: Response): Promise<T> => (await res.json()) as T;

const authorizeAllow = vi.fn<WorkflowApiContext["authorize"]>();
const verifyTriggerSurvey = vi.fn<WorkflowApiContext["verifyTriggerSurvey"]>();
const verifyRecipientsAllowed = vi.fn<WorkflowApiContext["verifyRecipientsAllowed"]>();
const listUnreadableSurveyIds = vi.fn<WorkflowApiContext["listUnreadableSurveyIds"]>();
const verifySurveyLinkSurveys = vi.fn<WorkflowApiContext["verifySurveyLinkSurveys"]>();
const logger: WorkflowsLogger = { warn: vi.fn(), error: vi.fn() };

const authorized: AuthorizedWorkspace = { workspaceId, organizationId: "cm9zr5org00000000000000000" };

const makeCtx = (overrides: Partial<WorkflowApiContext> = {}): WorkflowApiContext => ({
  userId: "cm9zr52kh000508l8e3q7bw9j",
  requestId: "req_1",
  instance: "https://app.formbricks.com",
  logger,
  authorize: authorizeAllow,
  verifyTriggerSurvey,
  verifyRecipientsAllowed,
  listUnreadableSurveyIds,
  verifySurveyLinkSurveys,
  ...overrides,
});

const deniedResponse = (): Response =>
  Response.json(
    { title: "Forbidden", status: 403, detail: "denied", requestId: "req_1", code: "forbidden" },
    { status: 403, headers: { "Content-Type": "application/problem+json" } }
  );

beforeEach(() => {
  vi.clearAllMocks();
  authorizeAllow.mockResolvedValue(authorized);
  verifyTriggerSurvey.mockResolvedValue({ surveyExists: true, missingEndingCardIds: [] });
  verifyRecipientsAllowed.mockResolvedValue({ disallowedEmails: [] });
  listUnreadableSurveyIds.mockResolvedValue([]);
  verifySurveyLinkSurveys.mockResolvedValue([]);
});

describe("get", () => {
  test("returns 403 (not 404) when the workflow does not exist", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.get({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(403);
    expect(authorizeAllow).not.toHaveBeenCalled();
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("forbidden");
  });

  test("returns the denial response when the caller lacks workspace access", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    const ctx = makeCtx({ authorize: vi.fn().mockResolvedValue(deniedResponse()) });

    const res = await handlers.get({ ctx, params: { workflowId } });

    expect(res.status).toBe(403);
  });

  test("returns 200 with the workflow resource on success", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());

    const res = await handlers.get({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(res.headers.get("X-Request-Id")).toBe("req_1");
    const body = await readJson<{ data: { id: string; triggerType: string; definition: unknown } }>(res);
    expect(body.data.id).toBe(workflowId);
    expect(body.data.triggerType).toBe("response.completed");
    expect(body.data.definition).toBeDefined();
  });

  test("returns 500 when the serialized output fails its resource schema", async () => {
    const badRow = makeRow({
      definition: {
        ...definition,
        trigger: { ...definition.trigger, config: { surveyId: "not-a-cuid", endingCardIds: [] } },
      },
    });
    service.getWorkflowById.mockResolvedValue(badRow);

    const res = await handlers.get({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(500);
    expect(logger.error).toHaveBeenCalled();
  });
});

describe("create", () => {
  const postRequest = (body: unknown): Request =>
    new Request("http://localhost/api/v3/workflows", {
      method: "POST",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });

  test("creates a draft and returns 201 with a Location header", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(201);
    expect(res.headers.get("Location")).toBe(`/api/v3/workflows/${workflowId}`);
    expect(service.createWorkflow).toHaveBeenCalledWith(expect.objectContaining({ workspaceId }), {
      createdBy: "cm9zr52kh000508l8e3q7bw9j",
    });
  });

  test("rejects an invalid definition with 400 and invalid_params", async () => {
    const res = await handlers.create({
      req: postRequest({
        workspaceId,
        name: "Broken",
        definition: { schemaVersion: 1, trigger: {}, nodes: [], edges: [], entryNodeId: "trigger" },
      }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    const body = await readJson<{ code: string; invalid_params: unknown }>(res);
    expect(body.code).toBe("bad_request");
    expect(Array.isArray(body.invalid_params)).toBe(true);
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });

  test("refuses a definition over the step limit with 400, naming the limit", async () => {
    const emailNode = definition.nodes[0];
    const nodes = Array.from({ length: 26 }, (_, index) => ({ ...emailNode, id: `email-${index}` }));
    const edges = nodes.map((node, index) => ({
      id: `edge-${index}`,
      source: index === 0 ? "trigger" : `email-${index - 1}`,
      target: node.id,
    }));

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Too long", definition: { ...definition, nodes, edges } }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    const body = await readJson<{ invalid_params: { reason: string }[] }>(res);
    expect(JSON.stringify(body.invalid_params)).toMatch(/at most 25 steps/);
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });

  test("refuses an If/else over the condition limit with 400", async () => {
    const conditions = Array.from({ length: 21 }, (_, index) => ({
      id: `c${index}`,
      left: { path: "response.q1" },
      operator: "isSet",
    }));
    const overLimit = {
      ...definition,
      nodes: [
        { id: "check", type: "if_else", config: { condition: { id: "g", connector: "and", conditions } } },
      ],
      edges: [{ id: "e1", source: "trigger", target: "check" }],
    };

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Too many conditions", definition: overLimit }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    expect(JSON.stringify(await readJson(res))).toMatch(/at most 20 conditions/);
  });

  test("returns the denial response without creating when access is missing", async () => {
    const ctx = makeCtx({ authorize: vi.fn().mockResolvedValue(deniedResponse()) });

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx,
    });

    expect(res.status).toBe(403);
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a malformed JSON body with 400", async () => {
    const req = new Request("http://localhost/api/v3/workflows", {
      method: "POST",
      body: "{ not valid json",
      headers: { "Content-Type": "application/json" },
    });

    const res = await handlers.create({ req, ctx: makeCtx() });

    expect(res.status).toBe(400);
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a body that exceeds the size limit with 400", async () => {
    const oversizedName = "x".repeat(2 * 1024 * 1024 + 1);

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: oversizedName, definition }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });
});

describe("list", () => {
  const listRequest = (query: string): Request => new Request(`http://localhost/api/v3/workflows?${query}`);

  test("returns 200 with a cursor-paginated envelope", async () => {
    service.listWorkflows.mockResolvedValue({ workflows: [makeRow()], nextCursor: null, totalCount: null });

    const res = await handlers.list({
      req: listRequest(`workspaceId=${workspaceId}&sortBy=name`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(200);
    const body = await readJson<{
      data: unknown[];
      meta: { limit: number; nextCursor: string | null; totalCount: number | null };
    }>(res);
    expect(body.data).toHaveLength(1);
    expect(body.meta.limit).toBe(20);
    expect(body.meta.nextCursor).toBeNull();
    expect(body.meta.totalCount).toBeNull();
    expect(service.listWorkflows).toHaveBeenCalledWith(expect.objectContaining({ includeTotalCount: false }));
  });

  test("passes includeTotalCount through and echoes the total in meta", async () => {
    service.listWorkflows.mockResolvedValue({ workflows: [makeRow()], nextCursor: null, totalCount: 7 });

    const res = await handlers.list({
      req: listRequest(`workspaceId=${workspaceId}&includeTotalCount=true`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(200);
    const body = await readJson<{ meta: { totalCount: number | null } }>(res);
    expect(body.meta.totalCount).toBe(7);
    expect(service.listWorkflows).toHaveBeenCalledWith(expect.objectContaining({ includeTotalCount: true }));
  });

  test("rejects a non-boolean includeTotalCount with 400", async () => {
    const res = await handlers.list({
      req: listRequest(`workspaceId=${workspaceId}&includeTotalCount=yes`),
      ctx: makeCtx(),
    });
    expect(res.status).toBe(400);
    expect(service.listWorkflows).not.toHaveBeenCalled();
  });

  test("rejects an out-of-range limit with 400", async () => {
    const res = await handlers.list({
      req: listRequest(`workspaceId=${workspaceId}&limit=500`),
      ctx: makeCtx(),
    });
    expect(res.status).toBe(400);
    expect(service.listWorkflows).not.toHaveBeenCalled();
  });

  /** Postgres `text` cannot hold U+0000; let through, the name filter fails the query with a 500 (ENG-3550). */
  test("rejects a NULL byte in the name filter with 400", async () => {
    const res = await handlers.list({
      req: listRequest(`workspaceId=${workspaceId}&filter[name][contains]=a%00b`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    const body = await readJson<{ invalid_params: unknown[] }>(res);
    expect(body.invalid_params).toEqual([{ name: "nameContains", reason: "must not contain NULL bytes" }]);
    expect(service.listWorkflows).not.toHaveBeenCalled();
  });

  test("returns the denial response when access is missing", async () => {
    const ctx = makeCtx({ authorize: vi.fn().mockResolvedValue(deniedResponse()) });
    const res = await handlers.list({ req: listRequest(`workspaceId=${workspaceId}`), ctx });
    expect(res.status).toBe(403);
    expect(service.listWorkflows).not.toHaveBeenCalled();
  });
});

describe("patch", () => {
  const patchRequest = (body: unknown): Request =>
    new Request("http://localhost/api/v3/workflows/x", {
      method: "PATCH",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });

  test("updates name on a draft workflow and returns 200", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.updateWorkflow.mockResolvedValue(makeRow({ name: "Renamed" }));

    const res = await handlers.patch({
      req: patchRequest({ name: "Renamed" }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(200);
    expect(service.updateWorkflow).toHaveBeenCalledWith(
      { workflowId, workspaceId },
      { name: "Renamed", issueWebhookToken: false }
    );
  });

  test("allows name/description edits on an enabled workflow", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    service.updateWorkflow.mockResolvedValue(makeRow({ status: "enabled", description: "x" }));

    const res = await handlers.patch({
      req: patchRequest({ description: "x" }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(200);
    expect(service.updateWorkflow).toHaveBeenCalled();
  });

  test("rejects a definition edit on an enabled workflow with 422", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.patch({
      req: patchRequest({ definition }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("invalid_workflow_state");
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("rejects any patch on an archived workflow with 422", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));

    const res = await handlers.patch({
      req: patchRequest({ name: "x" }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(422);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("rejects an empty patch with 400", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));

    const res = await handlers.patch({ req: patchRequest({}), ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(400);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("returns 403 for an unknown workflow", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.patch({
      req: patchRequest({ name: "x" }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(403);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });
});

describe("duplicate", () => {
  const emptyPost = (): Request =>
    new Request("http://localhost/api/v3/workflows/x/duplicate", { method: "POST" });

  test("creates a copy and returns 201 with a Location header", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    service.duplicateWorkflow.mockResolvedValue(makeRow());

    const res = await handlers.duplicate({ req: emptyPost(), ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(201);
    expect(res.headers.get("Location")).toBe(`/api/v3/workflows/${workflowId}`);
    expect(service.duplicateWorkflow).toHaveBeenCalledWith(expect.objectContaining({ id: workflowId }), {
      name: undefined,
      createdBy: "cm9zr52kh000508l8e3q7bw9j",
    });
  });
});

describe("a stored definition that predates the save-time rules", () => {
  // 26 steps (over the limit of 25) and an If/else whose path the Variable path rule refuses: both
  // could be saved before the rules existed, so they must keep reading; writing them is refused.
  const emailNode = definition.nodes[0];
  const nodes = [
    {
      id: "check",
      type: "if_else" as const,
      config: {
        condition: {
          id: "g",
          connector: "and" as const,
          conditions: [{ id: "c1", left: { path: "data.q1" }, operator: "exists" as const }],
        },
      },
    },
    ...Array.from({ length: 25 }, (_, index) => ({ ...emailNode, id: `email-${index}` })),
  ];
  const edges = [
    { id: "e-check", source: "trigger", target: "check" },
    { id: "e-then", source: "check", target: "email-0", sourceHandle: "then" },
    ...nodes.slice(2).map((node, index) => ({ id: `e-${index}`, source: `email-${index}`, target: node.id })),
  ];
  const stored = { ...definition, nodes, edges };
  const emptyPost = (): Request =>
    new Request("http://localhost/api/v3/workflows/x/duplicate", { method: "POST" });

  test("reads with 200", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ definition: stored }));

    const res = await handlers.get({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
  });

  test("disables and archives with 200", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled", definition: stored }));
    service.disableWorkflow.mockResolvedValue(makeRow({ status: "disabled", definition: stored }));
    expect((await handlers.disable({ ctx: makeCtx(), params: { workflowId } })).status).toBe(200);

    service.getWorkflowById.mockResolvedValue(makeRow({ status: "disabled", definition: stored }));
    service.setStatus.mockResolvedValue(makeRow({ status: "archived", definition: stored }));
    expect((await handlers.archive({ ctx: makeCtx(), params: { workflowId } })).status).toBe(200);
  });

  test("saving it is refused with 400", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ definition: stored }));

    const res = await handlers.patch({
      req: new Request("http://localhost/api/v3/workflows/x", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ definition: stored }),
      }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(400);
    const body = await readJson<{ invalid_params: unknown }>(res);
    expect(JSON.stringify(body.invalid_params)).toMatch(/at most 25 steps/);
    expect(JSON.stringify(body.invalid_params)).toMatch(/payload\., steps\., response\./);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("duplicating it is refused with 400", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ definition: stored }));

    const res = await handlers.duplicate({ req: emptyPost(), ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(400);
    expect(service.duplicateWorkflow).not.toHaveBeenCalled();
  });

  test("enabling it is refused with 422 workflow_not_executable", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "disabled", definition: stored }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: unknown }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(JSON.stringify(body.invalid_params)).toMatch(/at most 25 steps/);
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });
});

describe("trigger survey attach-time guard (ENG-3283)", () => {
  const otherSurveyId = "cm9zr4q7i000108l84gozfggs";
  const restricted = { surveyExists: true, missingEndingCardIds: [], surveyNotWorkspaceVisible: true };
  const jsonRequest = (method: string, body: unknown): Request =>
    new Request("http://localhost/api/v3/workflows", {
      method,
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });
  const boundTo = (id: string) => ({
    ...definition,
    trigger: { ...definition.trigger, config: { surveyId: id, endingCardIds: [] } },
  });

  const expectRefused = async (res: Response) => {
    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: Array<{ name: string }> }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params).toEqual([
      expect.objectContaining({ name: "definition.trigger.config.surveyId" }),
    ]);
  };

  test("create refuses a draft bound to a survey the workspace cannot see", async () => {
    verifyTriggerSurvey.mockResolvedValue(restricted);

    const res = await handlers.create({
      req: jsonRequest("POST", { workspaceId, name: "Notify team", definition }),
      ctx: makeCtx(),
    });

    await expectRefused(res);
    expect(verifyTriggerSurvey).toHaveBeenCalledWith({ workspaceId, surveyId, endingCardIds: [] });
    expect(service.createWorkflow).not.toHaveBeenCalled();
  });

  test("patch refuses pointing the trigger at a survey the workspace cannot see", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue(restricted);

    const res = await handlers.patch({
      req: jsonRequest("PATCH", { definition: boundTo(otherSurveyId) }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    await expectRefused(res);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("patch keeps an existing binding editable: an unchanged trigger survey is not re-checked", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.updateWorkflow.mockResolvedValue(makeRow());
    verifyTriggerSurvey.mockResolvedValue(restricted);

    const res = await handlers.patch({
      req: jsonRequest("PATCH", { definition: boundTo(surveyId) }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(200);
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
  });

  test("duplicate refuses copying a workflow bound to a survey the workspace cannot see", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    verifyTriggerSurvey.mockResolvedValue(restricted);

    const res = await handlers.duplicate({
      req: new Request("http://localhost/api/v3/workflows/x/duplicate", { method: "POST" }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    await expectRefused(res);
    expect(service.duplicateWorkflow).not.toHaveBeenCalled();
  });

  test("a workspace-visible trigger survey is accepted on create", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());

    const res = await handlers.create({
      req: jsonRequest("POST", { workspaceId, name: "Notify team", definition }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(201);
    expect(verifyTriggerSurvey).toHaveBeenCalledOnce();
  });
});

describe("delete", () => {
  test("hard-deletes and returns 204", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    service.deleteWorkflow.mockResolvedValue(undefined);

    const res = await handlers.delete({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(204);
    expect(service.deleteWorkflow).toHaveBeenCalledWith({ workflowId, workspaceId });
  });

  test("returns 403 for an unknown workflow without deleting", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.delete({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(403);
    expect(service.deleteWorkflow).not.toHaveBeenCalled();
  });
});

describe("archive / unarchive", () => {
  test("archives a draft workflow", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.setStatus.mockResolvedValue(makeRow({ status: "archived" }));

    const res = await handlers.archive({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(service.setStatus).toHaveBeenCalledWith({ workflowId, workspaceId }, "archived");
  });

  test("rejects archiving an already-archived workflow with 422", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));

    const res = await handlers.archive({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    expect(service.setStatus).not.toHaveBeenCalled();
  });

  test("unarchives an archived workflow back to draft", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));
    service.setStatus.mockResolvedValue(makeRow({ status: "draft" }));

    const res = await handlers.unarchive({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(service.setStatus).toHaveBeenCalledWith({ workflowId, workspaceId }, "draft");
  });

  test("rejects unarchiving a non-archived workflow with 422", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));

    const res = await handlers.unarchive({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    expect(service.setStatus).not.toHaveBeenCalled();
  });
});

describe("a Switch step (ENG-7157)", () => {
  const emailNode = definition.nodes[0];
  const withSwitch = (cases: { id: string; name: string }[]) => ({
    ...definition,
    nodes: [
      {
        id: "route",
        type: "switch" as const,
        config: {
          left: { path: "response.plan" },
          cases: cases.map((switchCase) => ({
            ...switchCase,
            operator: "equals" as const,
            right: switchCase.id,
          })),
        },
      },
      { ...emailNode, id: "gold-email" },
      { ...emailNode, id: "default-email" },
    ],
    edges: [
      { id: "e1", source: "trigger", target: "route" },
      { id: "e2", source: "route", target: "gold-email", sourceHandle: "gold" },
      { id: "e3", source: "route", target: "default-email", sourceHandle: "default" },
    ],
  });
  const goldAndSilver = withSwitch([
    { id: "gold", name: "Gold" },
    { id: "silver", name: "Silver" },
  ]);

  test("is created with 201 and read back as written", async () => {
    service.createWorkflow.mockResolvedValue(makeRow({ definition: goldAndSilver }));

    const res = await handlers.create({
      req: new Request("http://localhost/api/v3/workflows", {
        method: "POST",
        body: JSON.stringify({ workspaceId, name: "Route by plan", definition: goldAndSilver }),
        headers: { "Content-Type": "application/json" },
      }),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(201);
    const body = await readJson<{ data: { definition: { nodes: { config: unknown }[] } } }>(res);
    expect(body.data.definition.nodes[0].config).toEqual(goldAndSilver.nodes[0].config);
  });

  test("a change to more than 10 cases is refused with 400", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ definition: goldAndSilver }));
    const elevenCases = withSwitch(
      Array.from({ length: 11 }, (_, index) => ({
        id: index === 0 ? "gold" : `case-${index}`,
        name: `Case ${index}`,
      }))
    );

    const res = await handlers.patch({
      req: new Request(`http://localhost/api/v3/workflows/${workflowId}`, {
        method: "PATCH",
        body: JSON.stringify({ definition: elevenCases }),
        headers: { "Content-Type": "application/json" },
      }),
      ctx: makeCtx(),
      params: { workflowId },
    });

    expect(res.status).toBe(400);
    expect(JSON.stringify(await readJson(res))).toMatch(/at most 10 cases/);
    expect(service.updateWorkflow).not.toHaveBeenCalled();
  });

  test("is enabled with 200", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft", definition: goldAndSilver }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled", definition: goldAndSilver }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
  });

  test("enabling with an unnamed case is refused with 422 workflow_not_executable", async () => {
    const unnamed = withSwitch([
      { id: "gold", name: "Gold" },
      { id: "silver", name: "" },
    ]);
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft", definition: unnamed }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    expect(JSON.stringify(await readJson(res))).toMatch(/workflow_not_executable/);
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });
});

describe("enable", () => {
  test("snapshots a version and returns 200 when enabling a draft", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(verifyTriggerSurvey).toHaveBeenCalledWith({ workspaceId, surveyId, endingCardIds: [] });
    expect(service.enableWorkflow).toHaveBeenCalledWith(
      { workflowId, workspaceId },
      expect.objectContaining({ publishedBy: "cm9zr52kh000508l8e3q7bw9j" })
    );
    const body = await readJson<{ data: { status: string } }>(res);
    expect(body.data.status).toBe("enabled");
  });

  test("re-enables a disabled workflow", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "disabled" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(service.enableWorkflow).toHaveBeenCalled();
  });

  test("records a null publishedBy for API-key callers", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    await handlers.enable({ ctx: makeCtx({ userId: null }), params: { workflowId } });

    expect(service.enableWorkflow.mock.calls[0][1].publishedBy).toBeNull();
  });

  test("rejects enabling an already-enabled workflow with 422 invalid_workflow_state", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("invalid_workflow_state");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("rejects enabling an archived workflow with 422 invalid_workflow_state", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("invalid_workflow_state");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a non-executable (trigger-only) definition with 422 workflow_not_executable", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({ status: "draft", definition: { ...definition, nodes: [], edges: [] } })
    );

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: unknown[] }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(Array.isArray(body.invalid_params)).toBe(true);
    expect(body.invalid_params.length).toBeGreaterThan(0);
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a missing trigger survey with 422 workflow_not_executable", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue({ surveyExists: false, missingEndingCardIds: [] });

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: { name: string }[] }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params.map((p) => p.name)).toContain("definition.trigger.config.surveyId");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a trigger survey that is not workspace-visible with 422 workflow_not_executable", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue({
      surveyExists: true,
      missingEndingCardIds: [],
      surveyNotWorkspaceVisible: true,
    });

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: { name: string }[] }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params.map((p) => p.name)).toContain("definition.trigger.config.surveyId");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("rejects a missing ending card with 422 workflow_not_executable", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue({ surveyExists: true, missingEndingCardIds: ["ec_missing"] });

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: { name: string }[] }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params.map((p) => p.name)).toContain("definition.trigger.config.endingCardIds");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("checks literal send_email recipients against the workspace allowlist and rejects an external one (ENG-2029)", async () => {
    // Default definition's send_email targets a literal address (support@example.com).
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyRecipientsAllowed.mockResolvedValue({ disallowedEmails: ["support@example.com"] });

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(verifyRecipientsAllowed).toHaveBeenCalledWith({
      workspaceId,
      emails: ["support@example.com"],
    });
    expect(res.status).toBe(422);
    const body = await readJson<{
      code: string;
      detail: string;
      invalid_params: { name: string }[];
    }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params.map((p) => p.name)).toContain("definition.nodes.config.to");
    // `detail` must name the cause on its own: the editor's error mapper surfaces only `detail`.
    expect(body.detail).toBe("A send_email recipient cannot access this workspace.");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("allows enabling when the literal recipient can access the workspace", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));
    verifyRecipientsAllowed.mockResolvedValue({ disallowedEmails: [] });

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(service.enableWorkflow).toHaveBeenCalled();
  });

  test("skips the recipient allowlist check when the recipient is a respondent field (not a literal email)", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({
        status: "draft",
        definition: {
          ...definition,
          nodes: [
            {
              ...definition.nodes[0],
              config: { ...definition.nodes[0].config, to: "email-question-id" },
            },
          ],
        },
      })
    );
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(verifyRecipientsAllowed).not.toHaveBeenCalled();
    expect(service.enableWorkflow).toHaveBeenCalled();
  });

  test("maps a concurrent-enable conflict from the service to 409", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockRejectedValue(new WorkflowConflictError());

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(409);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("conflict");
  });

  test("returns 403 for an unknown workflow without enabling", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(403);
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });
});

describe("disable", () => {
  test("disables an enabled workflow and returns 200", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    service.disableWorkflow.mockResolvedValue(makeRow({ status: "disabled" }));

    const res = await handlers.disable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(service.disableWorkflow).toHaveBeenCalledWith({ workflowId, workspaceId });
    const body = await readJson<{ data: { status: string } }>(res);
    expect(body.data.status).toBe("disabled");
  });

  test("rejects disabling a draft workflow with 422 invalid_workflow_state", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));

    const res = await handlers.disable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("invalid_workflow_state");
    expect(service.disableWorkflow).not.toHaveBeenCalled();
  });

  test("returns 403 for an unknown workflow without disabling", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.disable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(403);
    expect(service.disableWorkflow).not.toHaveBeenCalled();
  });
});

interface TestResultBody {
  data: { workflowId: string; ok: boolean; problems: { code: string; field: string; message: string }[] };
}

describe("testWorkflow", () => {
  test("returns ok=true for an executable enabled workflow with a valid trigger survey", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(verifyTriggerSurvey).toHaveBeenCalledWith({ workspaceId, surveyId, endingCardIds: [] });
    const body = await readJson<TestResultBody>(res);
    expect(body.data).toEqual({ workflowId, ok: true, problems: [], warnings: [] });
  });

  test("authorizes at read — it is a dry run and the MCP tool is workflows:read scoped", async () => {
    // ENG-2223: this authorized at "readWrite", so a read-scoped caller got a 403 from a tool that
    // persists nothing. Raising it back means moving test_workflow's declared MCP scope with it.
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));

    await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(authorizeAllow).toHaveBeenCalledWith(workspaceId, "read");
  });

  test("tests a disabled workflow", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "disabled" }));

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(true);
  });

  test("tests a draft workflow (dry-run before going live)", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(true);
  });

  test("rejects an archived workflow with 422 invalid_workflow_state without checking the survey", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(422);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("invalid_workflow_state");
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
  });

  test("collects every executability issue in one pass without throwing", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({ status: "enabled", definition: { ...definition, nodes: [], edges: [] } })
    );

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(false);
    expect(body.data.problems.map((p) => p.code)).toContain("definition_not_executable");
  });

  test("reports a trigger survey that is not workspace-visible", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue({
      surveyExists: true,
      missingEndingCardIds: [],
      surveyNotWorkspaceVisible: true,
    });

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(false);
    expect(body.data.problems.map((p) => p.code)).toContain("survey_not_workspace_visible");
  });

  test("skips the survey check when the definition is not executable", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({ status: "enabled", definition: { ...definition, nodes: [], edges: [] } })
    );
    verifyTriggerSurvey.mockResolvedValue({ surveyExists: false, missingEndingCardIds: [] });

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    // The trigger config is read from the validated `executable.data`, never the raw persisted
    // JSON, so an unparseable definition never reaches (and never throws in) the survey check.
    expect(res.status).toBe(200);
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
    const codes = (await readJson<TestResultBody>(res)).data.problems.map((p) => p.code);
    expect(codes).toContain("definition_not_executable");
    expect(codes).not.toContain("survey_not_found");
  });

  test("reports an incomplete send_email action as not executable", async () => {
    const incompleteEmailDefinition = {
      ...definition,
      nodes: [
        {
          ...definition.nodes[0],
          config: { ...definition.nodes[0].config, to: "", subject: "", body: "" },
        },
      ],
    };
    service.getWorkflowById.mockResolvedValue(
      makeRow({ status: "enabled", definition: incompleteEmailDefinition })
    );

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(false);
    const fields = body.data.problems
      .filter((p) => p.code === "definition_not_executable")
      .map((p) => p.field);
    expect(fields).toEqual(
      expect.arrayContaining(["nodes.0.config.to", "nodes.0.config.subject", "nodes.0.config.body"])
    );
  });

  test("reports a missing ending card", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    verifyTriggerSurvey.mockResolvedValue({ surveyExists: true, missingEndingCardIds: ["ec_missing"] });

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(false);
    const problem = body.data.problems.find((p) => p.code === "ending_card_not_found");
    expect(problem?.field).toBe("definition.trigger.config.endingCardIds");
  });

  test("reports a non-member literal recipient as a problem instead of testing green (ENG-2029)", async () => {
    // Default definition's send_email targets a literal address (support@example.com).
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyRecipientsAllowed.mockResolvedValue({ disallowedEmails: ["support@example.com"] });

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(verifyRecipientsAllowed).toHaveBeenCalledWith({ workspaceId, emails: ["support@example.com"] });
    expect(res.status).toBe(200);
    const body = await readJson<TestResultBody>(res);
    expect(body.data.ok).toBe(false);
    const problem = body.data.problems.find((p) => p.code === "recipient_not_allowed");
    expect(problem?.field).toBe("definition.nodes.config.to");
    expect(problem?.message).toContain("support@example.com");
  });

  test("skips the recipient check for a respondent-field recipient", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({
        status: "draft",
        definition: {
          ...definition,
          nodes: [
            {
              ...definition.nodes[0],
              config: { ...definition.nodes[0].config, to: "email-question-id" },
            },
          ],
        },
      })
    );

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(verifyRecipientsAllowed).not.toHaveBeenCalled();
    expect((await readJson<TestResultBody>(res)).data.ok).toBe(true);
  });

  test("skips the recipient check when the definition is not executable", async () => {
    service.getWorkflowById.mockResolvedValue(
      makeRow({ status: "enabled", definition: { ...definition, nodes: [], edges: [] } })
    );

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    expect(verifyRecipientsAllowed).not.toHaveBeenCalled();
  });

  test("returns 403 for an unknown workflow without checking the survey", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(403);
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
  });

  test("returns the authorization denial without checking the survey", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    const ctx = makeCtx({ authorize: vi.fn().mockResolvedValue(deniedResponse()) });

    const res = await handlers.testWorkflow({ ctx, params: { workflowId } });

    expect(res.status).toBe(403);
    expect(verifyTriggerSurvey).not.toHaveBeenCalled();
  });
});

describe("survey link checks on enable and test (ENG-7180)", () => {
  const linkSurveyId = "cm9zr4mps000008l8linksrvy";
  const withSurveyLink = makeRow({
    status: "draft",
    definition: {
      ...definition,
      nodes: [
        {
          ...definition.nodes[0],
          config: {
            ...definition.nodes[0].config,
            body: "<p>Tell us: #survey-link#</p>",
            surveyLink: {
              surveyId: linkSurveyId,
              embeddedData: [
                { key: "agent_id", value: "A-42" },
                { key: "call_id", value: "K-771" },
              ],
            },
          },
        },
      ],
    },
  });

  test("enable refuses a survey link to a survey that is not a link survey in the workspace", async () => {
    service.getWorkflowById.mockResolvedValue(withSurveyLink);
    verifySurveyLinkSurveys.mockResolvedValue([
      { surveyId: linkSurveyId, status: "not_link", acceptedEmbeddedDataKeys: [] },
    ]);

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(verifySurveyLinkSurveys).toHaveBeenCalledWith({ workspaceId, surveyIds: [linkSurveyId] });
    expect(res.status).toBe(422);
    const body = await readJson<{ code: string; invalid_params: { name: string }[] }>(res);
    expect(body.code).toBe("workflow_not_executable");
    expect(body.invalid_params.map((p) => p.name)).toContain("definition.nodes.0.config.surveyLink.surveyId");
    expect(service.enableWorkflow).not.toHaveBeenCalled();
  });

  test("enable succeeds and warns about Embedded Data keys the survey does not accept", async () => {
    service.getWorkflowById.mockResolvedValue(withSurveyLink);
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));
    verifySurveyLinkSurveys.mockResolvedValue([
      { surveyId: linkSurveyId, status: "ok", acceptedEmbeddedDataKeys: ["Agent_ID"] },
    ]);

    const res = await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(res.status).toBe(200);
    const body = await readJson<{ meta?: { warnings: { code: string; field: string; message: string }[] } }>(
      res
    );
    // Matched case-insensitively, as the link survey does; only call_id is undeclared.
    const warnings = body.meta?.warnings ?? [];
    expect(warnings.map(({ code, field }) => ({ code, field }))).toEqual([
      {
        code: "survey_link_key_not_accepted",
        field: "definition.nodes.0.config.surveyLink.embeddedData.1.key",
      },
    ]);
    expect(warnings[0]?.message).toContain("call_id");
  });

  test("the test check reports a missing link survey as a problem and undeclared keys as warnings", async () => {
    service.getWorkflowById.mockResolvedValue(withSurveyLink);
    verifySurveyLinkSurveys.mockResolvedValue([
      { surveyId: linkSurveyId, status: "not_found", acceptedEmbeddedDataKeys: [] },
    ]);

    const res = await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } });

    const body = await readJson<{
      data: TestResultBody["data"] & { warnings: { code: string }[] };
    }>(res);
    expect(body.data.ok).toBe(false);
    expect(body.data.problems.map((p) => p.code)).toContain("survey_link_survey_not_found");

    verifySurveyLinkSurveys.mockResolvedValue([
      { surveyId: linkSurveyId, status: "ok", acceptedEmbeddedDataKeys: ["agent_id"] },
    ]);
    const okBody = await readJson<{ data: TestResultBody["data"] & { warnings: { code: string }[] } }>(
      await handlers.testWorkflow({ ctx: makeCtx(), params: { workflowId } })
    );
    expect(okBody.data.ok).toBe(true);
    expect(okBody.data.warnings.map((w) => w.code)).toEqual(["survey_link_key_not_accepted"]);
  });

  test("a workflow without a survey link never looks one up", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    await handlers.enable({ ctx: makeCtx(), params: { workflowId } });

    expect(verifySurveyLinkSurveys).not.toHaveBeenCalled();
  });
});

describe("recordAudit (audit-sink port)", () => {
  const copyId = "cm9zr4t2b000208l8h2m1xyz9";
  const recordAudit = vi.fn<NonNullable<WorkflowApiContext["recordAudit"]>>();
  const auditCtx = (overrides: Partial<WorkflowApiContext> = {}): WorkflowApiContext =>
    makeCtx({ recordAudit, ...overrides });

  const postRequest = (body?: unknown): Request =>
    new Request("http://localhost/api/v3/workflows", {
      method: "POST",
      ...(body !== undefined
        ? { body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }
        : {}),
    });
  const patchRequest = (body: unknown): Request =>
    new Request("http://localhost/api/v3/workflows/x", {
      method: "PATCH",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });

  test("create surfaces the new id and a new-object snapshot (no old object)", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());

    await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: auditCtx(),
    });

    expect(recordAudit).toHaveBeenCalledTimes(1);
    const detail = recordAudit.mock.calls[0][0];
    expect(detail.targetId).toBe(workflowId);
    expect(detail.workspaceId).toBe(workspaceId);
    expect(detail.oldObject).toBeUndefined();
    expect(detail.newObject).toEqual(expect.objectContaining({ id: workflowId, workspaceId }));
  });

  test("update surfaces before/after snapshots showing the changed name", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft", name: "Before" }));
    service.updateWorkflow.mockResolvedValue(makeRow({ name: "After" }));

    await handlers.patch({ req: patchRequest({ name: "After" }), ctx: auditCtx(), params: { workflowId } });

    expect(recordAudit).toHaveBeenCalledTimes(1);
    const detail = recordAudit.mock.calls[0][0];
    expect(detail.targetId).toBe(workflowId);
    expect(detail.oldObject).toEqual(expect.objectContaining({ name: "Before" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ name: "After" }));
  });

  test("delete surfaces the removed object (no new object)", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    service.deleteWorkflow.mockResolvedValue(undefined);

    await handlers.delete({ ctx: auditCtx(), params: { workflowId } });

    expect(recordAudit).toHaveBeenCalledTimes(1);
    const detail = recordAudit.mock.calls[0][0];
    expect(detail.targetId).toBe(workflowId);
    expect(detail.oldObject).toEqual(expect.objectContaining({ id: workflowId }));
    expect(detail.newObject).toBeUndefined();
  });

  test("duplicate surfaces the copy's id, not the source id", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    service.duplicateWorkflow.mockResolvedValue(makeRow({ id: copyId, name: "Notify team (copy)" }));

    await handlers.duplicate({
      req: new Request("http://localhost/api/v3/workflows/x/duplicate", { method: "POST" }),
      ctx: auditCtx(),
      params: { workflowId },
    });

    expect(recordAudit).toHaveBeenCalledTimes(1);
    const detail = recordAudit.mock.calls[0][0];
    expect(detail.targetId).toBe(copyId);
    expect(detail.oldObject).toBeUndefined();
    expect(detail.newObject).toEqual(expect.objectContaining({ id: copyId }));
  });

  test("enable surfaces the draft -> enabled status transition in both snapshots", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: "enabled" }));

    await handlers.enable({ ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    expect(detail.oldObject).toEqual(expect.objectContaining({ status: "draft" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ status: "enabled" }));
  });

  test("disable surfaces the enabled -> disabled status transition", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    service.disableWorkflow.mockResolvedValue(makeRow({ status: "disabled" }));

    await handlers.disable({ ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    expect(detail.oldObject).toEqual(expect.objectContaining({ status: "enabled" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ status: "disabled" }));
  });

  test("archive surfaces the * -> archived status transition", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.setStatus.mockResolvedValue(makeRow({ status: "archived" }));

    await handlers.archive({ ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    expect(detail.oldObject).toEqual(expect.objectContaining({ status: "draft" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ status: "archived" }));
  });

  test("unarchive surfaces the archived -> draft status transition", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));
    service.setStatus.mockResolvedValue(makeRow({ status: "draft" }));

    await handlers.unarchive({ ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    expect(detail.oldObject).toEqual(expect.objectContaining({ status: "archived" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ status: "draft" }));
  });

  test("redacts send_email PII in the snapshot definition while keeping the diff readable", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft", name: "Before" }));
    service.updateWorkflow.mockResolvedValue(makeRow({ status: "draft", name: "After" }));

    await handlers.patch({ req: patchRequest({ name: "After" }), ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    // Emails from the definition fixture must not leak into either snapshot.
    expect(JSON.stringify(detail.oldObject)).not.toContain("@example.com");
    expect(JSON.stringify(detail.newObject)).not.toContain("@example.com");
    // The non-PII change is still readable.
    expect(detail.oldObject).toEqual(expect.objectContaining({ name: "Before" }));
    expect(detail.newObject).toEqual(expect.objectContaining({ name: "After" }));
    // The send_email recipient is masked (present), not dropped.
    const newDef = (detail.newObject as { definition: { nodes: { config: { to: string } }[] } }).definition;
    expect(newDef.nodes[0].config.to).toMatch(/^\[redacted:[0-9a-f]{12}]$/);
  });

  test("a recipient-only edit still surfaces as a change (masked, not collapsed)", async () => {
    const withRecipient = (to: string): WorkflowRowWithLastRun =>
      makeRow({
        status: "draft",
        definition: {
          ...definition,
          nodes: [{ ...definition.nodes[0], config: { ...definition.nodes[0].config, to } }],
        },
      });
    service.getWorkflowById.mockResolvedValue(withRecipient("old@example.com"));
    service.updateWorkflow.mockResolvedValue(withRecipient("new@example.com"));

    await handlers.patch({ req: patchRequest({ definition }), ctx: auditCtx(), params: { workflowId } });

    const detail = recordAudit.mock.calls[0][0];
    const readTo = (snapshot: unknown): string =>
      (snapshot as { definition: { nodes: { config: { to: string } }[] } }).definition.nodes[0].config.to;
    const oldTo = readTo(detail.oldObject);
    const newTo = readTo(detail.newObject);

    // Distinct value-stable markers → a recipient change still diffs, but no raw email leaks.
    expect(oldTo).not.toBe(newTo);
    expect(oldTo).not.toContain("@example.com");
    expect(newTo).not.toContain("@example.com");
  });

  test("is not called on a failed mutation (unknown workflow)", async () => {
    service.getWorkflowById.mockResolvedValue(null);

    await handlers.delete({ ctx: auditCtx(), params: { workflowId } });

    expect(recordAudit).not.toHaveBeenCalled();
  });

  test("a missing sink (no adapter wired) is a no-op, mutation still succeeds", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: makeCtx({ recordAudit: undefined }),
    });

    expect(res.status).toBe(201);
  });

  test("a throwing sink is swallowed: the already-successful mutation still returns success", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());
    const throwingSink = vi.fn().mockRejectedValue(new Error("audit backend down"));

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: auditCtx({ recordAudit: throwingSink }),
    });

    expect(res.status).toBe(201);
    expect(throwingSink).toHaveBeenCalledTimes(1);
    expect(logger.error).toHaveBeenCalled();
  });
});

describe("recordAnalytics (analytics-sink port)", () => {
  const copyId = "cm9zr4t2b000208l8h2m1xyz9";
  const recordAnalytics = vi.fn<NonNullable<WorkflowApiContext["recordAnalytics"]>>();
  const analyticsCtx = (overrides: Partial<WorkflowApiContext> = {}): WorkflowApiContext =>
    makeCtx({ recordAnalytics, ...overrides });

  const postRequest = (body?: unknown): Request =>
    new Request("http://localhost/api/v3/workflows", {
      method: "POST",
      ...(body !== undefined
        ? { body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }
        : {}),
    });

  // The shape summary every detail carries for the shared test `definition` (one trigger, one email).
  const expectedShape = {
    definition: {
      triggerType: "response.completed",
      actionTypes: ["send_email"],
      actionCount: 1,
      nodeCount: 2,
    },
    options: {
      endingScope: "all",
      emailRecipientKind: "literal",
      attachResponseData: true,
      includeVariables: false,
      includeHiddenFields: false,
    },
  };

  test("create reports the new workflow with its shape and no previous status", async () => {
    service.createWorkflow.mockResolvedValue(makeRow({ status: "draft" }));

    await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: analyticsCtx(),
    });

    expect(recordAnalytics).toHaveBeenCalledTimes(1);
    const detail = recordAnalytics.mock.calls[0][0];
    expect(detail).toEqual(
      expect.objectContaining({
        operation: "created",
        workflowId,
        workspaceId,
        status: "draft",
        ...expectedShape,
      })
    );
    expect(detail.createdAt).toBeInstanceOf(Date);
    expect(detail.previousStatus).toBeUndefined();
  });

  test("duplicate reports the copy and names the source", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow());
    service.duplicateWorkflow.mockResolvedValue(makeRow({ id: copyId, status: "draft" }));

    await handlers.duplicate({
      req: new Request("http://localhost/api/v3/workflows/x/duplicate", { method: "POST" }),
      ctx: analyticsCtx(),
      params: { workflowId },
    });

    expect(recordAnalytics.mock.calls[0][0]).toEqual(
      expect.objectContaining({ operation: "duplicated", workflowId: copyId, sourceWorkflowId: workflowId })
    );
  });

  test.each([
    ["enable", "draft", "enabled"],
    ["disable", "enabled", "disabled"],
    ["archive", "enabled", "archived"],
    ["unarchive", "archived", "draft"],
  ] as const)("%s reports the %s -> %s transition", async (handler, before, after) => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: before }));
    service.enableWorkflow.mockResolvedValue(makeRow({ status: after }));
    service.disableWorkflow.mockResolvedValue(makeRow({ status: after }));
    service.setStatus.mockResolvedValue(makeRow({ status: after }));

    await handlers[handler]({ ctx: analyticsCtx(), params: { workflowId } });

    expect(recordAnalytics).toHaveBeenCalledTimes(1);
    expect(recordAnalytics.mock.calls[0][0]).toEqual(
      expect.objectContaining({
        operation: `${handler}d`,
        status: after,
        previousStatus: before,
        ...expectedShape,
      })
    );
  });

  test("delete reports the removed row's last status", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "archived" }));
    service.deleteWorkflow.mockResolvedValue(undefined);

    await handlers.delete({ ctx: analyticsCtx(), params: { workflowId } });

    expect(recordAnalytics.mock.calls[0][0]).toEqual(
      expect.objectContaining({ operation: "deleted", workflowId, status: "archived" })
    );
    expect(recordAnalytics.mock.calls[0][0].previousStatus).toBeUndefined();
  });

  test("the test operation reports whether the dry run passed", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    verifyTriggerSurvey.mockResolvedValue({ surveyExists: false, missingEndingCardIds: [] });

    await handlers.testWorkflow({ ctx: analyticsCtx(), params: { workflowId } });

    expect(recordAnalytics.mock.calls[0][0]).toEqual(
      expect.objectContaining({ operation: "tested", workflowId, testOk: false })
    );
  });

  test("patch is deliberately not reported (autosave would fire it every few seconds)", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    service.updateWorkflow.mockResolvedValue(makeRow({ name: "After" }));

    await handlers.patch({
      req: new Request("http://localhost/api/v3/workflows/x", {
        method: "PATCH",
        body: JSON.stringify({ name: "After" }),
        headers: { "Content-Type": "application/json" },
      }),
      ctx: analyticsCtx(),
      params: { workflowId },
    });

    expect(recordAnalytics).not.toHaveBeenCalled();
  });

  test("the detail never carries the definition itself, only its shape", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());

    await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: analyticsCtx(),
    });

    const serialized = JSON.stringify(recordAnalytics.mock.calls[0][0]);
    expect(serialized).not.toContain("@example.com");
    expect(serialized).not.toContain("Thanks");
    expect(serialized).not.toContain("nodes");
  });

  test("is not called on a failed mutation (denied authorization)", async () => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "draft" }));
    authorizeAllow.mockResolvedValue(deniedResponse());

    await handlers.enable({ ctx: analyticsCtx(), params: { workflowId } });

    expect(recordAnalytics).not.toHaveBeenCalled();
  });

  test("a throwing sink is swallowed: the already-successful mutation still returns success", async () => {
    service.createWorkflow.mockResolvedValue(makeRow());
    const throwingSink = vi.fn().mockRejectedValue(new Error("analytics backend down"));

    const res = await handlers.create({
      req: postRequest({ workspaceId, name: "Notify team", definition }),
      ctx: analyticsCtx({ recordAnalytics: throwingSink }),
    });

    expect(res.status).toBe(201);
    expect(throwingSink).toHaveBeenCalledTimes(1);
    expect(logger.error).toHaveBeenCalled();
  });
});

const runId = "cm9zr4w9d000308l8c5n8xk7e";

const makeRunRow = (overrides: Partial<WorkflowRunRow> = {}): WorkflowRunRow => ({
  id: runId,
  createdAt: new Date("2026-06-12T10:00:00.000Z"),
  updatedAt: new Date("2026-06-12T10:01:00.000Z"),
  workflowId,
  workspaceId,
  workflowVersionId: null,
  responseId: null,
  status: "completed",
  triggerType: "response.completed",
  surveyId,
  isDryRun: false,
  attempt: 0,
  error: null,
  startedAt: new Date("2026-06-12T10:00:30.000Z"),
  finishedAt: new Date("2026-06-12T10:01:00.000Z"),
  ...overrides,
});

// The runs list serializer reads workflow.name; list rows are WorkflowRunListRow, not bare WorkflowRunRow.
const makeRunListRow = (overrides: Partial<WorkflowRunListRow> = {}): WorkflowRunListRow => ({
  ...makeRunRow(),
  workflow: { name: "My Workflow" },
  ...overrides,
});

// Mirrors the canonical run-data fixture's trigger payload (a valid TWorkflowTriggerRunPayload), so
// the handler's output validation against ZWorkflowRunResource passes.
const validTriggerPayload = {
  type: "response.completed",
  surveyId,
  responseId: "cm9zr4rsp000708l8bqccpfrx",
  endingCardId: "cm9zr4q7i000108l84gozfggr",
  workspaceId,
  data: { response: { email: "jane@example.com", score: 9 } },
  triggeredAt: "2026-06-09T12:01:00.000Z",
} as unknown as TWorkflowTriggerRunPayload;

const makeRunDetail = (overrides: Partial<WorkflowRunWithLogsRow> = {}): WorkflowRunWithLogsRow => ({
  ...makeRunRow(),
  triggerPayload: validTriggerPayload,
  data: { steps: [] },
  idempotencyKey: null,
  nextAttemptAt: null,
  lastErrorAt: null,
  callerIp: null,
  contentDeletedAt: null,
  contentRetentionDays: null,
  workflowVersion: null,
  logs: [
    {
      id: "cm9zr5log0000000000000000a",
      runId,
      sequence: 0,
      stepId: "send-email",
      stepType: "send_email",
      status: "succeeded",
      input: { to: "jane@example.com" },
      output: { messageId: "msg_1" },
      error: null,
      startedAt: new Date("2026-06-12T10:00:30.000Z"),
      finishedAt: new Date("2026-06-12T10:00:31.000Z"),
    },
  ],
  ...overrides,
});

describe("listRuns", () => {
  const runsRequest = (query: string): Request =>
    new Request(`http://localhost/api/v3/workflows/runs?${query}`);

  test("returns 200 with a cursor-paginated envelope of run summaries", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [makeRunListRow()], nextCursor: null });

    const res = await handlers.listRuns({ req: runsRequest(`workspaceId=${workspaceId}`), ctx: makeCtx() });

    expect(res.status).toBe(200);
    const body = await readJson<{
      data: { id: string; workflowName: string }[];
      meta: { limit: number; nextCursor: string | null };
    }>(res);
    expect(body.data).toHaveLength(1);
    expect(body.data[0].id).toBe(runId);
    // The list serializer joins the workflow name onto each row (ZWorkflowRunListItem).
    expect(body.data[0].workflowName).toBe("My Workflow");
    expect(body.meta.limit).toBe(20);
    expect(body.meta.nextCursor).toBeNull();
    expect(authorizeAllow).toHaveBeenCalledWith(workspaceId, "read");
  });

  test("forwards workflowId / responseId / status / isDryRun filters to the service", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [], nextCursor: null });

    await handlers.listRuns({
      req: runsRequest(
        `workspaceId=${workspaceId}&workflowId=${workflowId}&responseId=${responseId}&filter[status][in]=failed,completed&filter[isDryRun][eq]=true`
      ),
      ctx: makeCtx(),
    });

    expect(service.listWorkflowRuns).toHaveBeenCalledWith(
      expect.objectContaining({
        workspaceId,
        workflowId,
        responseId,
        statusIn: ["failed", "completed"],
        isDryRun: true,
      })
    );
  });

  test("forwards isDryRun=false alongside a status filter (falsy boolean not dropped)", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [], nextCursor: null });

    await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&filter[isDryRun][eq]=false&filter[status][in]=failed`),
      ctx: makeCtx(),
    });

    expect(service.listWorkflowRuns).toHaveBeenCalledWith(
      expect.objectContaining({ workspaceId, isDryRun: false, statusIn: ["failed"] })
    );
  });

  test("forwards a trigger filter, and refuses a trigger type that doesn't exist", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [], nextCursor: null });

    await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&filter[triggerType][in]=webhook`),
      ctx: makeCtx(),
    });
    expect(service.listWorkflowRuns).toHaveBeenCalledWith(
      expect.objectContaining({ workspaceId, triggerTypeIn: ["webhook"] })
    );

    const res = await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&filter[triggerType][in]=schedule`),
      ctx: makeCtx(),
    });
    expect(res.status).toBe(400);
  });

  test("returns an empty data array and null nextCursor for an empty page", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [], nextCursor: null });

    const res = await handlers.listRuns({ req: runsRequest(`workspaceId=${workspaceId}`), ctx: makeCtx() });

    expect(res.status).toBe(200);
    const body = await readJson<{ data: unknown[]; meta: { nextCursor: string | null } }>(res);
    expect(body.data).toEqual([]);
    expect(body.meta.nextCursor).toBeNull();
  });

  test("maps a WorkflowInvalidInputError from the service (e.g. malformed cursor) to 400", async () => {
    service.listWorkflowRuns.mockRejectedValue(new WorkflowInvalidInputError("malformed cursor"));

    const res = await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&cursor=not-base64url-json`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("bad_request");
  });

  test("rejects a missing workspaceId with 400 and never calls the service", async () => {
    const res = await handlers.listRuns({ req: runsRequest("limit=20"), ctx: makeCtx() });

    expect(res.status).toBe(400);
    expect(service.listWorkflowRuns).not.toHaveBeenCalled();
  });

  test("rejects an out-of-range limit with 400", async () => {
    const res = await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&limit=500`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    expect(service.listWorkflowRuns).not.toHaveBeenCalled();
  });

  test("rejects limit below the minimum (limit=0) with 400", async () => {
    const res = await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&limit=0`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(400);
    expect(service.listWorkflowRuns).not.toHaveBeenCalled();
  });

  test("accepts the minimum limit (limit=1)", async () => {
    service.listWorkflowRuns.mockResolvedValue({ runs: [makeRunListRow()], nextCursor: null });

    const res = await handlers.listRuns({
      req: runsRequest(`workspaceId=${workspaceId}&limit=1`),
      ctx: makeCtx(),
    });

    expect(res.status).toBe(200);
    expect(service.listWorkflowRuns).toHaveBeenCalledWith(expect.objectContaining({ limit: 1 }));
  });

  test("returns the authorize denial (403) and never calls the service", async () => {
    authorizeAllow.mockResolvedValue(deniedResponse());

    const res = await handlers.listRuns({ req: runsRequest(`workspaceId=${workspaceId}`), ctx: makeCtx() });

    expect(res.status).toBe(403);
    expect(service.listWorkflowRuns).not.toHaveBeenCalled();
    expect(listUnreadableSurveyIds).not.toHaveBeenCalled();
  });

  // ENG-3282: runs carry their trigger survey's response data, so they follow its visibility.
  test("excludes runs of surveys the caller may not read in the query, with one lookup per page", async () => {
    listUnreadableSurveyIds.mockResolvedValue([surveyId]);
    service.listWorkflowRuns.mockResolvedValue({ runs: [], nextCursor: null });

    await handlers.listRuns({ req: runsRequest(`workspaceId=${workspaceId}`), ctx: makeCtx() });

    expect(listUnreadableSurveyIds).toHaveBeenCalledTimes(1);
    expect(listUnreadableSurveyIds).toHaveBeenCalledWith({
      workspaceId,
      organizationId: authorized.organizationId,
    });
    expect(service.listWorkflowRuns).toHaveBeenCalledWith(
      expect.objectContaining({ workspaceId, excludeSurveyIds: [surveyId] })
    );
  });
});

describe("getRun", () => {
  test("returns 200 with the full run resource including ordered logs", async () => {
    service.getWorkflowRun.mockResolvedValue(makeRunDetail());

    const res = await handlers.getRun({ ctx: makeCtx(), params: { runId } });

    expect(res.status).toBe(200);
    const body = await readJson<{ data: { id: string; logs: { id: string }[]; triggerPayload: unknown } }>(
      res
    );
    expect(body.data.id).toBe(runId);
    expect(body.data.logs).toHaveLength(1);
    expect(body.data.triggerPayload).toMatchObject({ type: "response.completed", surveyId });
    expect(authorizeAllow).toHaveBeenCalledWith(workspaceId, "read");
  });

  test("returns 403 (not 404) when the run does not exist, without authorizing", async () => {
    service.getWorkflowRun.mockResolvedValue(null);

    const res = await handlers.getRun({ ctx: makeCtx(), params: { runId } });

    expect(res.status).toBe(403);
    expect(authorizeAllow).not.toHaveBeenCalled();
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("forbidden");
  });

  test("returns 403 for a run whose trigger survey the caller may not read", async () => {
    service.getWorkflowRun.mockResolvedValue(makeRunDetail());
    listUnreadableSurveyIds.mockResolvedValue([surveyId]);

    const res = await handlers.getRun({ ctx: makeCtx(), params: { runId } });

    expect(res.status).toBe(403);
    expect(listUnreadableSurveyIds).toHaveBeenCalledWith({
      workspaceId,
      organizationId: authorized.organizationId,
      surveyIds: [surveyId],
    });
    const body = await readJson<{ code: string; data?: unknown }>(res);
    expect(body.code).toBe("forbidden");
    expect(JSON.stringify(body)).not.toContain("jane@example.com");
  });

  test("returns a run without a trigger survey with no visibility lookup", async () => {
    service.getWorkflowRun.mockResolvedValue(makeRunDetail({ surveyId: null }));

    const res = await handlers.getRun({ ctx: makeCtx(), params: { runId } });

    expect(res.status).toBe(200);
    expect(listUnreadableSurveyIds).not.toHaveBeenCalled();
  });

  test("authorizes against the loaded run's workspace and returns its denial on mismatch", async () => {
    service.getWorkflowRun.mockResolvedValue(makeRunDetail({ workspaceId: "cm9zr4other00000000000000x" }));
    authorizeAllow.mockResolvedValue(deniedResponse());

    const res = await handlers.getRun({ ctx: makeCtx(), params: { runId } });

    expect(res.status).toBe(403);
    expect(authorizeAllow).toHaveBeenCalledWith("cm9zr4other00000000000000x", "read");
    const body = await readJson<{ code: string }>(res);
    expect(body.code).toBe("forbidden");
  });
});

// Negative controls for the authorization level itself. This PR lowered two handlers from
// "readWrite" to "read" after verifying they write nothing; without these, making the same move on a
// handler that DOES write would pass the whole suite — the level was previously asserted in only
// three places, all of them expecting "read".
describe("write handlers authorize at readWrite", () => {
  const jsonRequest = (method: string, body: unknown): Request =>
    new Request("http://localhost/api/v3/workflows/x", {
      method,
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    });

  const params = { workflowId };

  const writeHandlers: [string, () => Promise<Response>][] = [
    [
      "create",
      () =>
        handlers.create({ req: jsonRequest("POST", { workspaceId, name: "n", definition }), ctx: makeCtx() }),
    ],
    ["patch", () => handlers.patch({ req: jsonRequest("PATCH", { name: "n" }), ctx: makeCtx(), params })],
    ["duplicate", () => handlers.duplicate({ req: jsonRequest("POST", {}), ctx: makeCtx(), params })],
    ["delete", () => handlers.delete({ ctx: makeCtx(), params })],
    ["archive", () => handlers.archive({ ctx: makeCtx(), params })],
    ["unarchive", () => handlers.unarchive({ ctx: makeCtx(), params })],
    ["enable", () => handlers.enable({ ctx: makeCtx(), params })],
    ["disable", () => handlers.disable({ ctx: makeCtx(), params })],
  ];

  test.each(writeHandlers)("%s authorizes at readWrite", async (_name, invoke) => {
    service.getWorkflowById.mockResolvedValue(makeRow({ status: "enabled" }));
    service.createWorkflow.mockResolvedValue(makeRow());
    service.updateWorkflow.mockResolvedValue(makeRow());
    service.duplicateWorkflow.mockResolvedValue(makeRow());

    await invoke();

    expect(authorizeAllow).toHaveBeenCalledWith(workspaceId, "readWrite");
  });
});
