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

const { deleteTask } = vi.hoisted(() => ({ deleteTask: vi.fn() }));
vi.mock("@/api", () => ({
  projectManagementAPI: {
    deleteTask,
    updateTask: vi.fn(),
    createTask: vi.fn(),
  },
}));

import { useMdtodoTaskMutation } from "./useMdtodoTaskMutation";

describe("useMdtodoTaskMutation delete sentinel", () => {
  beforeEach(() => deleteTask.mockReset());

  it("returns the deleted taskRef only after a successful API response and refresh", async () => {
    deleteTask.mockResolvedValue({ ok: true, data: {} });
    const mutation = useMdtodoTaskMutation();
    const refresh = vi.fn().mockResolvedValue(undefined);
    await expect(
      mutation.deleteTask(
        "task-ref",
        { expectedFingerprint: "sha256:test" },
        refresh,
      ),
    ).resolves.toBe("task-ref");
    expect(refresh).toHaveBeenCalledOnce();
  });

  it("returns null and preserves a visible error on API failure", async () => {
    deleteTask.mockResolvedValue({ ok: false, error: "conflict", status: 409 });
    const mutation = useMdtodoTaskMutation();
    const refresh = vi.fn();
    await expect(
      mutation.deleteTask(
        "task-ref",
        { expectedFingerprint: "stale" },
        refresh,
      ),
    ).resolves.toBeNull();
    expect(refresh).not.toHaveBeenCalled();
    expect(mutation.taskMutationError.value).toBe("conflict");
  });
});
