import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { setEditorText } from "@src/lib/editor/helpers";
import { afterEach, describe, expect, it } from "vitest";

describe("setEditorText", () => {
    let container: HTMLDivElement;
    let view: EditorView;

    afterEach(() => {
        view?.destroy();
        container?.remove();
    });

    function createView(doc: string, anchor: number): EditorView {
        container = document.createElement("div");
        document.body.appendChild(container);

        return new EditorView({
            parent: container,
            state: EditorState.create({ doc, selection: { anchor, head: anchor } }),
        });
    }

    it("clamps the selection when replacing with shorter text", () => {
        view = createView("abcd", 4);

        expect(() => setEditorText(view, "ab")).not.toThrow();

        expect(view.state.doc.toString()).toBe("ab");
        expect(view.state.selection.main.head).toBe(2);
    });

    it("preserves a valid selection when replacing with longer text", () => {
        view = createView("ab", 2);

        setEditorText(view, "abcd");

        expect(view.state.doc.toString()).toBe("abcd");
        expect(view.state.selection.main.head).toBe(2);
    });
});
