import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { KVEditor } from "../KVEditor";

describe("KVEditor", () => {
  it("prevents renaming a key to a duplicate and shows an inline error", () => {
    const handleChange = vi.fn();
    render(
      <FluentProvider theme={webLightTheme}>
        <KVEditor entries={{ first: "1", second: "2" }} onChange={handleChange} />
      </FluentProvider>,
    );

    const firstKeyInput = screen.getByLabelText(/Setting name: first/i);
    fireEvent.change(firstKeyInput, { target: { value: "second" } });
    fireEvent.blur(firstKeyInput);

    expect(handleChange).not.toHaveBeenCalled();
    expect(screen.getByText(/already exists/i)).toBeInTheDocument();
  });

  it("commits a valid key rename on blur", () => {
    const handleChange = vi.fn();
    render(
      <FluentProvider theme={webLightTheme}>
        <KVEditor entries={{ first: "1", second: "2" }} onChange={handleChange} />
      </FluentProvider>,
    );

    const firstKeyInput = screen.getByLabelText(/Setting name: first/i);
    fireEvent.change(firstKeyInput, { target: { value: "primary" } });
    fireEvent.blur(firstKeyInput);

    expect(handleChange).toHaveBeenCalledWith({ primary: "1", second: "2" });
  });
});
