import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, expect, test, vi } from "vitest";

import { LibraryEditModal } from "@/features/libraries/components/library-edit-modal";

const { updateLibraryResourceMock } = vi.hoisted(() => ({
  updateLibraryResourceMock: vi.fn(),
}));

vi.mock("@/features/libraries/manage-resource", () => ({
  updateLibraryResource: updateLibraryResourceMock,
}));

beforeEach(() => {
  updateLibraryResourceMock.mockReset();
  updateLibraryResourceMock.mockResolvedValue({
    id: "12",
    backendId: 12,
    libraryType: "models",
    name: "Ava / Studio",
    description: "中性棚拍模特占位数据，用于提交页联调。",
    previewUri: "mock://libraries/models/ava",
    tags: ["女装", "半身", "mock"],
    files: [
      {
        id: 101,
        role: "thumbnail",
        url: "mock://libraries/models/ava",
      },
    ],
    isMock: false,
  });
});

test("uses backendId when saving resource metadata edits", async () => {
  render(
    <LibraryEditModal
      item={{
        id: "local-model-12",
        backendId: 12,
        libraryType: "models",
        name: "Ava / Studio",
        description: "中性棚拍模特占位数据，用于提交页联调。",
        previewUri: "mock://libraries/models/ava",
        tags: ["女装", "半身", "mock"],
        files: [
          {
            id: 101,
            role: "thumbnail",
            url: "mock://libraries/models/ava",
          },
        ],
        isMock: false,
      }}
      libraryType="models"
      open
      onClose={() => {}}
      onSaved={() => {}}
    />,
  );

  fireEvent.click(screen.getByRole("button", { name: "保存修改" }));

  await waitFor(() => {
    expect(updateLibraryResourceMock).toHaveBeenCalledWith(
      expect.objectContaining({
        resourceId: "12",
      }),
    );
  });
});
