import { afterEach, describe, expect, it } from "../test/testHarness";
import { useGenerationStore } from "./useGenerationStore";
import type { WebGenerationPreviewTask } from "../types";

function previewTask(id: string, status: WebGenerationPreviewTask["status"] = "running"): WebGenerationPreviewTask {
  return {
    id,
    title: "Task",
    type: "image",
    status,
    progress: status === "completed" ? 100 : 10,
    prompt: "prompt",
    createdAt: "2026-06-10T08:00:00.000Z",
    source: "server",
  };
}

describe("useGenerationStore task state", () => {
  afterEach(() => {
    useGenerationStore.setState({ queue: [], tasks: [] });
  });

  it("merges server preview tasks without duplicating local rows", () => {
    const store = useGenerationStore.getState();

    store.appendTask(previewTask("server-1"));
    store.mergeServerTasks([previewTask("server-1", "completed"), previewTask("server-2")]);

    const tasks = useGenerationStore.getState().tasks;
    expect(tasks.map((task) => task.id)).toEqual(["server-1", "server-2"]);
    expect(tasks[0].status).toBe("completed");
  });

  it("syncs running queue updates into matching preview tasks", () => {
    const store = useGenerationStore.getState();

    store.addTask({
      id: "local-task-1",
      taskId: "server-task-1",
      title: "Image",
      type: "image",
      status: "running",
      progress: 5,
      prompt: "prompt",
      createdAt: Date.now(),
      sourceView: "workbench",
    });

    expect(useGenerationStore.getState().tasks[0].id).toBe("server-task-1");
    expect(useGenerationStore.getState().tasks[0].status).toBe("running");

    store.updateTask("local-task-1", {
      status: "completed",
      progress: 100,
      resultUrl: "https://oss.example/result.png",
    });

    const task = useGenerationStore.getState().tasks[0];
    expect(task.status).toBe("completed");
    expect(task.progress).toBe(100);
    expect(task.outputUrl).toBe("https://oss.example/result.png");
  });

  it("clears preview tasks and running queue together", () => {
    const store = useGenerationStore.getState();

    store.appendTask(previewTask("server-task-1"));
    store.addTask({
      id: "local-task-1",
      title: "Image",
      type: "image",
      status: "running",
      progress: 5,
      prompt: "prompt",
      createdAt: Date.now(),
      sourceView: "workbench",
    });

    store.clearTasks();

    expect(useGenerationStore.getState().tasks).toEqual([]);
    expect(useGenerationStore.getState().queue).toEqual([]);
  });
});
