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

import { useWorldGen } from "./useWorldGen";

// 后端客户端与 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("useWorldGen", () => {
  beforeEach(() => {
    post.mockReset();
    toast.mockReset();
  });
  afterEach(() => vi.clearAllMocks());

  it("初始为 idle、无实体", () => {
    const { result } = renderHook(() => useWorldGen());
    expect(result.current.status).toBe("idle");
    expect(result.current.entities).toEqual([]);
  });

  it("生成成功：status 走到 done 并填充实体", async () => {
    const entities = [{ id: "e1", kind: "place", name: "雾港" }];
    post.mockResolvedValue({ data: { entities }, error: null });

    const { result } = renderHook(() => useWorldGen());
    await act(async () => {
      await result.current.generate("p1", "一个海港城市");
    });

    expect(result.current.status).toBe("done");
    expect(result.current.entities).toEqual(entities);
    expect(toast).not.toHaveBeenCalled();
  });

  it("data 为空时实体回退为空数组", async () => {
    post.mockResolvedValue({ data: { entities: null }, error: null });
    const { result } = renderHook(() => useWorldGen());
    await act(async () => {
      await result.current.generate("p1", "brief");
    });
    expect(result.current.status).toBe("done");
    expect(result.current.entities).toEqual([]);
  });

  it("后端返回 error：status=error 且弹错误 toast", async () => {
    post.mockResolvedValue({ data: null, error: { detail: "配额不足" } });
    const { result } = renderHook(() => useWorldGen());
    await act(async () => {
      await result.current.generate("p1", "brief");
    });
    expect(result.current.status).toBe("error");
    expect(toast).toHaveBeenCalledWith(expect.any(String), "error");
  });

  it("请求抛异常：status=error 且弹网络异常 toast", async () => {
    post.mockRejectedValue(new Error("network down"));
    const { result } = renderHook(() => useWorldGen());
    await act(async () => {
      await result.current.generate("p1", "brief");
    });
    expect(result.current.status).toBe("error");
    expect(toast).toHaveBeenCalledWith("生成请求异常，请检查网络。", "error");
  });

  it("reset 清回 idle 与空实体", async () => {
    post.mockResolvedValue({ data: { entities: [{ id: "e1" }] }, error: null });
    const { result } = renderHook(() => useWorldGen());
    await act(async () => {
      await result.current.generate("p1", "brief");
    });
    act(() => result.current.reset());
    expect(result.current.status).toBe("idle");
    expect(result.current.entities).toEqual([]);
  });
});
