import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { safeSetWidget } from "../widget-safe.js";

describe("safeSetWidget", () => {
	it("safeSetWidget_when_ui_missing_returns_false", () => {
		expect(safeSetWidget({}, "sf-health", ["ready"])).toBe(false);
		expect(safeSetWidget({ ui: {} }, "sf-health", ["ready"])).toBe(false);
	});

	it("safeSetWidget_when_setWidget_throws_returns_false", () => {
		const ctx = {
			ui: {
				setWidget() {
					throw new TypeError("host.setExtensionWidget is not a function");
				},
			},
		};

		expect(safeSetWidget(ctx, "sf-health", ["ready"])).toBe(false);
	});

	it("safeSetWidget_when_setWidget_exists_calls_it_and_returns_true", () => {
		const setWidget = vi.fn();
		const ctx = { ui: { setWidget } };

		expect(
			safeSetWidget(ctx, "sf-health", ["ready"], {
				placement: "belowEditor",
			}),
		).toBe(true);

		expect(setWidget).toHaveBeenCalledWith("sf-health", ["ready"], {
			placement: "belowEditor",
		});
	});

	it("auto_runtime_uses_safeSetWidget_for_progress_widget_cleanup", () => {
		const autoSource = readFileSync(
			join(process.cwd(), "src/resources/extensions/sf/auto.js"),
			"utf8",
		);

		expect(autoSource).not.toMatch(/\.setWidget\?\.\(/);
		expect(autoSource).not.toMatch(/\.setWidget\(/);
	});
});
