// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { useRefine } from "./useRefine";

// 后端客户端与 Toast 是 hook 的外部副作用边界，单测一律 mock。
const post = vi.fn();
const toast = vi.fn();
vi.mock("@/lib/api/client", () => ({ api: { POST: (...a: unknown[]) => post(...a) } }));
vi.mock("@/components/Toast", () => ({ useToast: () => toast }));

describe("useRefine", () => {
  beforeEach(() => {
    post.mockReset();
    toast.mockReset();
  });
  afterEach(() => vi.clearAllMocks());

  it("初始为 idle、无结果", () => {
    const { result } = renderHook(() => useRefine());
    expect(result.current.status).toBe("idle");
    expect(result.current.result).toBeNull();
  });

  it("回炉成功：status=done 并返回新旧 diff", async () => {
    post.mockResolvedValue({
      data: { original: "旧文", refined: "新文" },
      error: null,
    });

    const { result } = renderHook(() => useRefine());
    let outcome: unknown;
    await act(async () => {
      outcome = await result.current.refine("p1", 3, "旧文", "更紧凑");
    });

    expect(outcome).toEqual({ original: "旧文", refined: "新文" });
    expect(result.current.status).toBe("done");
    expect(result.current.result).toEqual({ original: "旧文", refined: "新文" });
    expect(toast).not.toHaveBeenCalled();
  });

  it("成功路径以 trim 后的段提交、可省略空指令", async () => {
    post.mockResolvedValue({
      data: { original: "段", refined: "改" },
      error: null,
    });

    const { result } = renderHook(() => useRefine());
    await act(async () => {
      await result.current.refine("p1", 1, "  段  ");
    });

    expect(post).toHaveBeenCalledWith(
      "/projects/{project_id}/chapters/{chapter_no}/refine",
      expect.objectContaining({ body: { segment: "段" } }),
    );
  });

  it("LLM_UNAVAILABLE：status=error 且提示去设置页", async () => {
    post.mockResolvedValue({
      data: null,
      error: { error: { code: "LLM_UNAVAILABLE" } },
    });

    const { result } = renderHook(() => useRefine());
    let outcome: unknown;
    await act(async () => {
      outcome = await result.current.refine("p1", 2, "段");
    });

    expect(outcome).toBeNull();
    expect(result.current.status).toBe("error");
    expect(toast).toHaveBeenCalledWith(
      "未配置提供商，请先去设置页连一家。",
      "error",
    );
  });

  it("其余后端错误：status=error 且弹通用回炉失败 toast", async () => {
    post.mockResolvedValue({
      data: null,
      error: { error: { code: "INTERNAL" } },
    });

    const { result } = renderHook(() => useRefine());
    await act(async () => {
      await result.current.refine("p1", 2, "段");
    });

    expect(result.current.status).toBe("error");
    expect(toast).toHaveBeenCalledWith("回炉失败，请稍后重试。", "error");
  });

  it("请求抛异常：status=error 且弹网络异常 toast", async () => {
    post.mockRejectedValue(new Error("network down"));

    const { result } = renderHook(() => useRefine());
    let outcome: unknown;
    await act(async () => {
      outcome = await result.current.refine("p1", 2, "段");
    });

    expect(outcome).toBeNull();
    expect(result.current.status).toBe("error");
    expect(toast).toHaveBeenCalledWith("回炉请求异常，请检查网络。", "error");
  });

  it("reset 清回 idle 与空结果", async () => {
    post.mockResolvedValue({
      data: { original: "a", refined: "b" },
      error: null,
    });

    const { result } = renderHook(() => useRefine());
    await act(async () => {
      await result.current.refine("p1", 1, "a");
    });
    act(() => result.current.reset());

    expect(result.current.status).toBe("idle");
    expect(result.current.result).toBeNull();
  });
});
