import { describe, expect, it } from "vitest";

import { createOperationalScheduledConditions } from "./scheduled-conditions";

describe("createOperationalScheduledConditions", () => {
  it("keeps a scheduled condition running during the previous gap window", () => {
    const conditions = createOperationalScheduledConditions(new Date("2026-07-07T11:43:30+08:00"));
    const runningCondition = conditions.find(
      (condition) => condition.kind === "condition" && condition.status === "running"
    );

    expect(runningCondition?.title).toBe("SCADA 数据诊断");
    expect(runningCondition?.durationMinutes).toBe(5);
    expect(runningCondition?.scheduledAt).toContain("T11:40:");
  });

  it("rolls the running condition into history when the next interval starts", () => {
    const conditions = createOperationalScheduledConditions(new Date("2026-07-07T11:45:30+08:00"));
    const previousCondition = conditions.find(
      (condition) => condition.kind === "condition" && condition.id.includes("scada-diagnosis-202607071140")
    );
    const currentCondition = conditions.find(
      (condition) => condition.kind === "condition" && condition.id.includes("scada-diagnosis-202607071145")
    );

    expect(previousCondition?.status).not.toBe("running");
    expect(previousCondition?.durationMinutes).toBe(5);
    expect(currentCondition?.status).toBe("running");
    expect(currentCondition?.durationMinutes).toBe(5);
  });

  it("labels the active work-order stage as executing", () => {
    const conditions = createOperationalScheduledConditions(new Date("2026-07-07T10:40:00+08:00"));
    const executingWorkOrder = conditions.find(
      (condition) =>
        condition.kind === "work_order" &&
        condition.stages.some(
          (stage) => stage.id === "execution" && stage.status === "current"
        )
    );

    expect(
      executingWorkOrder?.kind === "work_order"
        ? executingWorkOrder.stages.find((stage) => stage.id === "execution")?.title
        : undefined
    ).toBe("执行中");
  });

  it("moves completed field work into a waiting-for-reply state", () => {
    const conditions = createOperationalScheduledConditions(new Date("2026-07-07T10:40:00+08:00"));
    const awaitingReplyWorkOrder = conditions.find(
      (condition) =>
        condition.kind === "work_order" &&
        condition.stages.some((stage) => stage.id === "reply" && stage.status === "current")
    );

    expect(awaitingReplyWorkOrder?.status).toBe("awaiting_reply");
    expect(
      awaitingReplyWorkOrder?.kind === "work_order"
        ? awaitingReplyWorkOrder.stages.find((stage) => stage.id === "reply")?.title
        : undefined
    ).toBe("待复令");
  });
});
