import { beforeEach, describe, expect, test, vi } from "vitest";
import { WorkflowConflictError } from "../errors";
import type { TWorkflowTriggerRunPayload } from "../types/runs";
import type {
  WorkflowDelegate,
  WorkflowRowWithLastRun,
  WorkflowRunDelegate,
  WorkflowRunListRow,
  WorkflowRunRow,
  WorkflowRunWithLogsRow,
  WorkflowVersionDelegate,
  WorkflowsDb,
} from "./ports";
import { createWorkflowsService } from "./workflows.service";

const surveyId = "cm9zr4q7i000108l84gozfggr";
const workspaceId = "cm9zr4mps000008l8btfy1vtz";

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: "cm9zr4t2b000208l8h2m1aq3c",
  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 findMany = vi.fn<WorkflowDelegate["findMany"]>();
const findUnique = vi.fn<WorkflowDelegate["findUnique"]>();
const create = vi.fn<WorkflowDelegate["create"]>();
const update = vi.fn<WorkflowDelegate["update"]>();
const deleteFn = vi.fn<WorkflowDelegate["delete"]>();
const updateMany = vi.fn<WorkflowDelegate["updateMany"]>();
const count = vi.fn<WorkflowDelegate["count"]>();
const versionFindFirst = vi.fn<WorkflowVersionDelegate["findFirst"]>();
const versionCreate = vi.fn<WorkflowVersionDelegate["create"]>();
const runFindMany = vi.fn<WorkflowRunDelegate["findMany"]>();
const runFindUnique = vi.fn<WorkflowRunDelegate["findUnique"]>();
const runCreate = vi.fn<WorkflowRunDelegate["create"]>();
const workflow = { findMany, findUnique, create, update, delete: deleteFn, updateMany, count };
const workflowVersion = { findFirst: versionFindFirst, create: versionCreate };
const workflowRun = { findMany: runFindMany, findUnique: runFindUnique, create: runCreate };
const prisma: WorkflowsDb = {
  workflow,
  workflowVersion,
  workflowRun,
  workflowSample: { findUnique: vi.fn(), upsert: vi.fn() },
  $transaction: (fn) => fn({ workflow, workflowVersion }),
};
const service = createWorkflowsService({
  prisma,
  webhookTokens: { issue: () => ({ hash: "hash", encrypted: "encrypted" }), reveal: () => "token" },
});

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: "cm9zr4t2b000208l8h2m1aq3c",
  workspaceId,
  workflowVersionId: null,
  responseId: null,
  status: "completed",
  triggerType: "response.completed",
  surveyId,
  isDryRun: false,
  attempt: 0,
  error: null,
  startedAt: null,
  finishedAt: null,
  ...overrides,
});

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

const makeRunDetail = (overrides: Partial<WorkflowRunWithLogsRow> = {}): WorkflowRunWithLogsRow => ({
  ...makeRunRow(),
  triggerPayload: { triggeredAt: "2026-06-12T10:00:00.000Z" } as unknown as TWorkflowTriggerRunPayload,
  data: { steps: [] },
  idempotencyKey: null,
  nextAttemptAt: null,
  lastErrorAt: null,
  callerIp: null,
  contentDeletedAt: null,
  contentRetentionDays: null,
  workflowVersion: null,
  logs: [],
  ...overrides,
});

beforeEach(() => {
  vi.clearAllMocks();
});

describe("createWorkflow", () => {
  test("persists a draft with createdBy from the caller", async () => {
    const row = makeRow();
    create.mockResolvedValue(row);

    const result = await service.createWorkflow(
      { workspaceId, name: "Notify team", definition },
      { createdBy: "cm9zr52kh000508l8e3q7bw9j" }
    );

    const createArgs = create.mock.calls[0][0];
    expect(createArgs.data).toMatchObject({
      workspaceId,
      name: "Notify team",
      status: "draft",
      createdBy: "cm9zr52kh000508l8e3q7bw9j",
    });
    expect(createArgs.include).toEqual({
      runs: { take: 1, orderBy: { createdAt: "desc" } },
      creator: { select: { name: true } },
      _count: { select: { runs: { where: { isDryRun: false } } } },
      secrets: { select: { id: true, boundOrigin: true } },
    });
    expect(result).toBe(row);
  });

  test("stores createdBy as null for API-key callers", async () => {
    create.mockResolvedValue(makeRow());
    await service.createWorkflow({ workspaceId, name: "X", definition }, { createdBy: null });
    expect(create.mock.calls[0][0].data.createdBy).toBeNull();
  });
});

describe("listWorkflows", () => {
  test("excludes archived workflows by default and over-fetches by one", async () => {
    findMany.mockResolvedValue([makeRow()]);

    const page = await service.listWorkflows({
      workspaceId,
      limit: 20,
      sortBy: "updatedAt",
      includeTotalCount: false,
    });

    const findManyArgs = findMany.mock.calls[0][0];
    expect(findManyArgs.where).toMatchObject({ workspaceId, status: { not: "archived" } });
    expect(findManyArgs.take).toBe(21);
    expect(findManyArgs.orderBy).toEqual([{ updatedAt: "desc" }, { id: "desc" }]);
    expect(page.nextCursor).toBeNull();
    expect(page.workflows).toHaveLength(1);
  });

  test("counts only real runs for the Runs column, never Test runs", async () => {
    findMany.mockResolvedValue([makeRow()]);

    await service.listWorkflows({ workspaceId, limit: 20, sortBy: "updatedAt", includeTotalCount: false });

    expect(findMany.mock.calls[0][0].include._count).toEqual({
      select: { runs: { where: { isDryRun: false } } },
    });
  });

  test("honors an explicit status filter", async () => {
    findMany.mockResolvedValue([]);
    await service.listWorkflows({
      workspaceId,
      limit: 20,
      sortBy: "updatedAt",
      includeTotalCount: false,
      statusIn: ["draft", "disabled"],
    });
    expect(findMany.mock.calls[0][0].where).toMatchObject({ status: { in: ["draft", "disabled"] } });
  });

  test("applies a case-insensitive name filter", async () => {
    findMany.mockResolvedValue([]);
    await service.listWorkflows({
      workspaceId,
      limit: 20,
      sortBy: "name",
      includeTotalCount: false,
      nameContains: "csat",
    });
    const findManyArgs = findMany.mock.calls[0][0];
    expect(findManyArgs.where).toMatchObject({ name: { contains: "csat", mode: "insensitive" } });
    expect(findManyArgs.orderBy).toEqual([{ name: "asc" }, { id: "asc" }]);
  });

  test("returns a next cursor when there are more rows than the limit", async () => {
    const rows = [
      makeRow({ id: "cm9zr4t2b000208l8h2m1aq30", updatedAt: new Date("2026-06-12T09:30:00.000Z") }),
      makeRow({ id: "cm9zr4t2b000208l8h2m1aq31", updatedAt: new Date("2026-06-11T09:30:00.000Z") }),
      makeRow({ id: "cm9zr4t2b000208l8h2m1aq32", updatedAt: new Date("2026-06-10T09:30:00.000Z") }),
    ];
    findMany.mockResolvedValue(rows);

    const page = await service.listWorkflows({
      workspaceId,
      limit: 2,
      sortBy: "updatedAt",
      includeTotalCount: false,
    });

    expect(page.workflows).toHaveLength(2);
    expect(page.nextCursor).toEqual(expect.any(String));
  });

  test("does not count unless includeTotalCount is set", async () => {
    findMany.mockResolvedValue([makeRow()]);

    const page = await service.listWorkflows({
      workspaceId,
      limit: 20,
      sortBy: "updatedAt",
      includeTotalCount: false,
    });

    expect(count).not.toHaveBeenCalled();
    expect(page.totalCount).toBeNull();
  });

  test("counts the same filters without the cursor when includeTotalCount is set", async () => {
    findMany.mockResolvedValue([makeRow()]);
    count.mockResolvedValue(42);
    const first = await service.listWorkflows({
      workspaceId,
      limit: 1,
      sortBy: "updatedAt",
      includeTotalCount: false,
    });
    findMany.mockResolvedValue([
      makeRow({ id: "cm9zr4t2b000208l8h2m1aq30", updatedAt: new Date("2026-06-12T09:30:00.000Z") }),
      makeRow({ id: "cm9zr4t2b000208l8h2m1aq31", updatedAt: new Date("2026-06-11T09:30:00.000Z") }),
    ]);
    const withCursor = await service.listWorkflows({
      workspaceId,
      limit: 1,
      sortBy: "updatedAt",
      includeTotalCount: false,
    });
    expect(first.totalCount).toBeNull();
    // A later page must really carry a cursor, or this would not prove the count ignores it.
    expect(withCursor.nextCursor).not.toBeNull();

    const page = await service.listWorkflows({
      workspaceId,
      limit: 1,
      sortBy: "updatedAt",
      includeTotalCount: true,
      statusIn: ["draft"],
      cursor: withCursor.nextCursor ?? undefined,
    });

    expect(page.totalCount).toBe(42);
    expect(count).toHaveBeenCalledTimes(1);
    const countWhere = count.mock.calls[0][0].where;
    expect(countWhere).toEqual({ workspaceId, status: { in: ["draft"] } });
  });
});

describe("getWorkflowById", () => {
  test("loads a single row by id with its last run and its secrets' origins", async () => {
    const row = makeRow();
    findUnique.mockResolvedValue(row);

    expect(await service.getWorkflowById(row.id)).toBe(row);
    expect(findUnique).toHaveBeenCalledWith({
      where: { id: row.id },
      include: {
        runs: { take: 1, orderBy: { createdAt: "desc" } },
        creator: { select: { name: true } },
        _count: { select: { runs: { where: { isDryRun: false } } } },
        secrets: { select: { id: true, boundOrigin: true } },
      },
    });
  });

  test("returns null when the workflow does not exist", async () => {
    findUnique.mockResolvedValue(null);
    expect(await service.getWorkflowById("missing")).toBeNull();
  });
});

describe("updateWorkflow", () => {
  test("updates only the provided fields by composite key", async () => {
    update.mockResolvedValue(makeRow({ name: "Renamed" }));

    await service.updateWorkflow(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
      { name: "Renamed" }
    );

    const args = update.mock.calls[0][0];
    expect(args.where).toEqual({
      id_workspaceId: { id: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
    });
    expect(args.data).toEqual({ name: "Renamed" });
  });

  test("passes through an explicit null description but omits absent fields", async () => {
    update.mockResolvedValue(makeRow());
    await service.updateWorkflow(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
      { description: null }
    );
    expect(update.mock.calls[0][0].data).toEqual({ description: null });
  });
});

describe("duplicateWorkflow", () => {
  const uniqueViolation = (): Error & { code: string } =>
    Object.assign(new Error("Unique constraint failed"), { code: "P2002" });

  test("clones into a new draft with a default copy name", async () => {
    create.mockResolvedValue(makeRow());
    await service.duplicateWorkflow(makeRow({ name: "Original" }), { createdBy: "user_1" });

    expect(create.mock.calls[0][0].data).toMatchObject({
      workspaceId,
      name: "Original (copy)",
      status: "draft",
      createdBy: "user_1",
    });
  });

  test("retries past a taken copy name and persists '<name> (copy 2)'", async () => {
    const duplicated = makeRow({ name: "Original (copy 2)" });
    create.mockRejectedValueOnce(uniqueViolation()).mockResolvedValueOnce(duplicated);

    const result = await service.duplicateWorkflow(makeRow({ name: "Original" }), { createdBy: "user_1" });

    expect(create).toHaveBeenCalledTimes(2);
    expect(create.mock.calls[0][0].data.name).toBe("Original (copy)");
    expect(create.mock.calls[1][0].data.name).toBe("Original (copy 2)");
    expect(result).toBe(duplicated);
  });

  test("rethrows a non-unique error without retrying", async () => {
    const boom = new Error("connection reset");
    create.mockRejectedValueOnce(boom);

    await expect(service.duplicateWorkflow(makeRow({ name: "Original" }), { createdBy: null })).rejects.toBe(
      boom
    );
    expect(create).toHaveBeenCalledTimes(1);
  });

  test("honors an explicit duplicate name with a single create", async () => {
    create.mockResolvedValue(makeRow());
    await service.duplicateWorkflow(makeRow({ name: "Original" }), { name: "Custom", createdBy: null });
    expect(create).toHaveBeenCalledTimes(1);
    expect(create.mock.calls[0][0].data.name).toBe("Custom");
  });

  test("does not retry an explicit name — a P2002 propagates to the caller", async () => {
    const conflict = uniqueViolation();
    create.mockRejectedValueOnce(conflict);

    await expect(
      service.duplicateWorkflow(makeRow({ name: "Original" }), { name: "Custom", createdBy: null })
    ).rejects.toBe(conflict);
    expect(create).toHaveBeenCalledTimes(1);
  });

  test("throws a conflict after exhausting all copy-name retries", async () => {
    // Every attempt collides, so the bounded retry loop gives up and surfaces a clean conflict.
    create.mockRejectedValue(uniqueViolation());

    await expect(
      service.duplicateWorkflow(makeRow({ name: "Original" }), { createdBy: null })
    ).rejects.toThrow("Could not find an available copy name for this workflow.");
    expect(create).toHaveBeenCalledTimes(50);
  });
});

describe("deleteWorkflow", () => {
  test("hard-deletes by composite key", async () => {
    deleteFn.mockResolvedValue({ id: "cm9zr4t2b000208l8h2m1aq3c" });
    await service.deleteWorkflow({ workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId });
    expect(deleteFn).toHaveBeenCalledWith({
      where: { id_workspaceId: { id: "cm9zr4t2b000208l8h2m1aq3c", workspaceId } },
    });
  });
});

describe("setStatus", () => {
  test("updates status by composite key", async () => {
    update.mockResolvedValue(makeRow({ status: "archived" }));
    await service.setStatus({ workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId }, "archived");
    const args = update.mock.calls[0][0];
    expect(args.where).toEqual({ id_workspaceId: { id: "cm9zr4t2b000208l8h2m1aq3c", workspaceId } });
    expect(args.data).toEqual({ status: "archived" });
  });
});

describe("enableWorkflow", () => {
  test("guards the transition then snapshots version max+1 in one transaction", async () => {
    updateMany.mockResolvedValue({ count: 1 });
    versionFindFirst.mockResolvedValue({ version: 3 });
    findUnique.mockResolvedValue(makeRow({ status: "enabled" }));

    const result = await service.enableWorkflow(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
      { definition, publishedBy: "cm9zr52kh000508l8e3q7bw9j" }
    );

    // The status guard runs inside the transaction, scoped to draft/disabled rows only.
    expect(updateMany.mock.calls[0][0]).toEqual({
      where: { id: "cm9zr4t2b000208l8h2m1aq3c", workspaceId, status: { in: ["draft", "disabled"] } },
      data: { status: "enabled" },
    });
    expect(versionCreate.mock.calls[0][0].data).toMatchObject({
      workflowId: "cm9zr4t2b000208l8h2m1aq3c",
      workspaceId,
      version: 4,
      publishedBy: "cm9zr52kh000508l8e3q7bw9j",
    });
    expect(result.status).toBe("enabled");
  });

  test("uses version 1 when no prior version exists and stores null publishedBy", async () => {
    updateMany.mockResolvedValue({ count: 1 });
    versionFindFirst.mockResolvedValue(null);
    findUnique.mockResolvedValue(makeRow({ status: "enabled" }));

    await service.enableWorkflow(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
      { definition, publishedBy: null }
    );

    expect(versionCreate.mock.calls[0][0].data.version).toBe(1);
    expect(versionCreate.mock.calls[0][0].data.publishedBy).toBeNull();
  });

  test("rejects with a conflict (and writes no version) when the guard matches no row", async () => {
    updateMany.mockResolvedValue({ count: 0 });

    await expect(
      service.enableWorkflow(
        { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
        { definition, publishedBy: null }
      )
    ).rejects.toBeInstanceOf(WorkflowConflictError);
    expect(versionCreate).not.toHaveBeenCalled();
  });

  test("maps a simultaneous-enable unique violation (P2002) to a conflict error", async () => {
    updateMany.mockResolvedValue({ count: 1 });
    versionFindFirst.mockResolvedValue({ version: 1 });
    versionCreate.mockRejectedValue(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }));

    await expect(
      service.enableWorkflow(
        { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
        { definition, publishedBy: null }
      )
    ).rejects.toBeInstanceOf(WorkflowConflictError);
  });

  test("rethrows non-unique transaction errors unchanged", async () => {
    updateMany.mockResolvedValue({ count: 1 });
    const boom = new Error("connection reset");
    versionFindFirst.mockRejectedValue(boom);

    await expect(
      service.enableWorkflow(
        { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId },
        { definition, publishedBy: null }
      )
    ).rejects.toBe(boom);
  });
});

describe("disableWorkflow", () => {
  test("sets status to disabled by composite key", async () => {
    update.mockResolvedValue(makeRow({ status: "disabled" }));
    await service.disableWorkflow({ workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId });
    const args = update.mock.calls[0][0];
    expect(args.where).toEqual({ id_workspaceId: { id: "cm9zr4t2b000208l8h2m1aq3c", workspaceId } });
    expect(args.data).toEqual({ status: "disabled" });
  });
});

describe("listWorkflowRuns", () => {
  test("scopes to the workspace, orders newest-first with an id tie-breaker, and over-fetches by one", async () => {
    runFindMany.mockResolvedValue([makeRunListRow()]);

    await service.listWorkflowRuns({ workspaceId, limit: 20 });

    const args = runFindMany.mock.calls[0][0];
    expect(args.where).toEqual({ workspaceId });
    expect(args.orderBy).toEqual([{ createdAt: "desc" }, { id: "desc" }]);
    expect(args.take).toBe(21);
    // List omits the large JSON columns and joins the workflow name (omit + include compose in Prisma).
    expect(args.omit).toEqual({ triggerPayload: true, data: true, testRunDefinition: true });
    expect(args.include).toEqual({ workflow: { select: { name: true } } });
  });

  test("applies workflowId, responseId, statusIn, triggerTypeIn, and isDryRun filters", async () => {
    runFindMany.mockResolvedValue([]);

    await service.listWorkflowRuns({
      workspaceId,
      limit: 20,
      workflowId: "cm9zr4t2b000208l8h2m1aq3c",
      responseId: "cm9zr5resp0000000000000000",
      statusIn: ["failed", "completed"],
      triggerTypeIn: ["webhook"],
      isDryRun: true,
    });

    expect(runFindMany.mock.calls[0][0].where).toEqual({
      workspaceId,
      workflowId: "cm9zr4t2b000208l8h2m1aq3c",
      responseId: "cm9zr5resp0000000000000000",
      status: { in: ["failed", "completed"] },
      triggerType: { in: ["webhook"] },
      isDryRun: true,
    });
  });

  test("leaves out runs of unreadable surveys in SQL, keeping runs with no survey", async () => {
    runFindMany.mockResolvedValue([]);
    const cursor = Buffer.from(
      JSON.stringify({ version: 1, value: "2026-06-12T10:00:00.000Z", id: "cm9zr5a0000000000000000002" }),
      "utf8"
    ).toString("base64url");

    await service.listWorkflowRuns({ workspaceId, limit: 20, cursor, excludeSurveyIds: ["s-1", "s-2"] });

    const { where } = runFindMany.mock.calls[0][0];
    // Nested under AND so the cursor's own OR survives; `IS NULL OR NOT IN` because NOT IN drops nulls.
    expect(where.AND).toEqual([{ OR: [{ surveyId: null }, { surveyId: { notIn: ["s-1", "s-2"] } }] }]);
    expect(where.OR).toHaveLength(2);
  });

  test("adds no survey clause when nothing is excluded", async () => {
    runFindMany.mockResolvedValue([]);
    await service.listWorkflowRuns({ workspaceId, limit: 20, excludeSurveyIds: [] });
    expect(runFindMany.mock.calls[0][0].where).toEqual({ workspaceId });
  });

  test("isDryRun: false is forwarded (excludes dry runs), not dropped", async () => {
    runFindMany.mockResolvedValue([]);
    await service.listWorkflowRuns({ workspaceId, limit: 20, isDryRun: false });
    expect(runFindMany.mock.calls[0][0].where.isDryRun).toBe(false);
  });

  test("combines responseId with isDryRun: false (both forwarded)", async () => {
    runFindMany.mockResolvedValue([]);
    await service.listWorkflowRuns({
      workspaceId,
      limit: 20,
      responseId: "cm9zr5resp0000000000000000",
      isDryRun: false,
    });
    expect(runFindMany.mock.calls[0][0].where).toEqual({
      workspaceId,
      responseId: "cm9zr5resp0000000000000000",
      isDryRun: false,
    });
  });

  test("returns no cursor when the page is not full", async () => {
    runFindMany.mockResolvedValue([makeRunListRow()]);
    const page = await service.listWorkflowRuns({ workspaceId, limit: 20 });
    expect(page.runs).toHaveLength(1);
    expect(page.nextCursor).toBeNull();
  });

  test("trims the over-fetched row and emits a next cursor from the last returned row", async () => {
    const older = makeRunListRow({
      id: "cm9zr5b0000000000000000001",
      createdAt: new Date("2026-06-12T09:00:00.000Z"),
    });
    const newest = makeRunListRow({
      id: "cm9zr5a0000000000000000002",
      createdAt: new Date("2026-06-12T10:00:00.000Z"),
    });
    // limit 1 → service over-fetches 2; only the first is returned, cursor points at it.
    runFindMany.mockResolvedValue([newest, older]);

    const page = await service.listWorkflowRuns({ workspaceId, limit: 1 });

    expect(page.runs).toHaveLength(1);
    expect(page.runs[0].id).toBe(newest.id);
    const { nextCursor } = page;
    if (nextCursor === null) {
      throw new Error("expected nextCursor to be present");
    }
    const decoded = JSON.parse(Buffer.from(nextCursor, "base64url").toString("utf8")) as {
      value: string;
      id: string;
    };
    expect(decoded).toEqual({ version: 1, value: "2026-06-12T10:00:00.000Z", id: newest.id });
  });

  test("at the page-size boundary (limit+1 rows) trims the extra row and points the cursor at the last kept row", async () => {
    const rows = [
      makeRunListRow({ id: "cm9zr5c0000000000000000003", createdAt: new Date("2026-06-12T10:00:00.000Z") }),
      makeRunListRow({ id: "cm9zr5c0000000000000000002", createdAt: new Date("2026-06-12T09:00:00.000Z") }),
      makeRunListRow({ id: "cm9zr5c0000000000000000001", createdAt: new Date("2026-06-12T08:00:00.000Z") }),
    ];
    // limit 2 → service over-fetches 3; exactly `limit` rows are returned and hasMore is true.
    runFindMany.mockResolvedValue(rows);

    const page = await service.listWorkflowRuns({ workspaceId, limit: 2 });

    expect(page.runs).toHaveLength(2);
    expect(page.runs.map((r) => r.id)).toEqual([rows[0].id, rows[1].id]);
    const { nextCursor } = page;
    if (nextCursor === null) {
      throw new Error("expected nextCursor to be present");
    }
    const decoded = JSON.parse(Buffer.from(nextCursor, "base64url").toString("utf8")) as {
      value: string;
      id: string;
    };
    expect(decoded).toEqual({ version: 1, value: "2026-06-12T09:00:00.000Z", id: rows[1].id });
  });

  test("decodes an incoming cursor into a keyset where-clause (older rows only)", async () => {
    runFindMany.mockResolvedValue([]);
    const cursor = Buffer.from(
      JSON.stringify({ version: 1, value: "2026-06-12T10:00:00.000Z", id: "cm9zr5a0000000000000000002" }),
      "utf8"
    ).toString("base64url");

    await service.listWorkflowRuns({ workspaceId, limit: 20, cursor });

    expect(runFindMany.mock.calls[0][0].where).toEqual({
      workspaceId,
      OR: [
        { createdAt: { lt: new Date("2026-06-12T10:00:00.000Z") } },
        { createdAt: new Date("2026-06-12T10:00:00.000Z"), id: { lt: "cm9zr5a0000000000000000002" } },
      ],
    });
  });

  test("rejects a malformed cursor before hitting the database", async () => {
    await expect(service.listWorkflowRuns({ workspaceId, limit: 20, cursor: "garbage" })).rejects.toThrow();
    expect(runFindMany).not.toHaveBeenCalled();
  });
});

describe("createTestRun", () => {
  test("saves a queued dry run with no version and the draft it runs, so nothing bills or dispatches it", async () => {
    runCreate.mockResolvedValue({ id: runId });
    const triggerPayload = {
      type: "webhook" as const,
      workspaceId: "cm9zr4mps000008l8btfy1vtz",
      payload: { order: 1 },
      triggeredAt: "2026-11-13T10:00:00.000Z",
    };

    const result = await service.createTestRun(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId: "cm9zr4mps000008l8btfy1vtz" },
      { triggerPayload, definition }
    );

    expect(result).toEqual({ id: runId });
    expect(runCreate).toHaveBeenCalledWith({
      data: {
        workflowId: "cm9zr4t2b000208l8h2m1aq3c",
        workspaceId: "cm9zr4mps000008l8btfy1vtz",
        workflowVersionId: null,
        status: "queued",
        triggerType: "webhook",
        isDryRun: true,
        attempt: 0,
        triggerPayload,
        testRunDefinition: definition,
      },
      select: { id: true },
    });
  });

  test("records a response run's survey and response, so the runs list's survey filter covers it", async () => {
    runCreate.mockResolvedValue({ id: runId });

    await service.createTestRun(
      { workflowId: "cm9zr4t2b000208l8h2m1aq3c", workspaceId: "cm9zr4mps000008l8btfy1vtz" },
      {
        triggerPayload: {
          type: "response.completed",
          workspaceId: "cm9zr4mps000008l8btfy1vtz",
          surveyId: "cm9zr4q7i000108l84gozfggr",
          responseId: "cm9zr5res000000000000000a",
          data: {},
          triggeredAt: "2026-11-13T10:00:00.000Z",
        },
        definition,
      }
    );

    expect(runCreate.mock.calls[0][0].data).toMatchObject({
      triggerType: "response.completed",
      surveyId: "cm9zr4q7i000108l84gozfggr",
      responseId: "cm9zr5res000000000000000a",
      isDryRun: true,
    });
  });
});

describe("getWorkflowRun", () => {
  test("loads a run by id and eager-loads its logs ordered by sequence", async () => {
    const detail = makeRunDetail({ logs: [] });
    runFindUnique.mockResolvedValue(detail);

    const result = await service.getWorkflowRun(runId);

    expect(runFindUnique.mock.calls[0][0]).toEqual({
      where: { id: runId },
      include: {
        logs: { orderBy: { sequence: "asc" } },
        workflowVersion: { select: { version: true } },
      },
    });
    expect(result).toBe(detail);
  });

  test("returns null when the run does not exist", async () => {
    runFindUnique.mockResolvedValue(null);
    expect(await service.getWorkflowRun(runId)).toBeNull();
  });
});
