import { describe, expect, it } from "vitest";
import { useProviderDialogs } from "../src/dimsdk/pages/utils/provider-dialogs.ts";

function createStoreWithCustomProvider() {
  const env: Record<string, string> = {};
  const toasts: string[] = [];

  const store: any = {
    state: {
      provider: {
        activeId: "cp_test",
        connections: {},
        activeModelByProvider: { cp_test: "model-a" },
        customProviders: [
          {
            id: "cp_test",
            name: "My Provider",
            adapter: "openai",
            baseUrl: "https://example.com/v1",
            apiKey: "sk-test",
            models: [{ id: "model-a" }],
          },
        ],
      },
      config: { model: "model-a" },
      context: { env: {} },
    },
    setEnvVar: (key: string, value: string | undefined) => {
      if (value == null) {
        delete env[key];
      } else {
        env[key] = String(value);
      }
    },
  };

  const dialogs = useProviderDialogs({
    store,
    nodeLike: false,
    showToast: (text: string) => toasts.push(text),
    openCustomSettings: () => {},
  });

  return { store, env, toasts, dialogs };
}

describe("provider dialogs custom provider manage menu", () => {
  it("supports rename and edit models", () => {
    const { store, toasts, dialogs } = createStoreWithCustomProvider();

    dialogs.openConnect();
    const customOpt = dialogs.providerOptions.value.find((o) => (o.keywords ?? []).includes("cp_test"));
    expect(customOpt).toBeTruthy();
    dialogs.onSelectProvider(customOpt!.label);
    expect(dialogs.showCustomManage.value).toBe(true);

    const renameOpt = dialogs.customManageOptions.value[1];
    dialogs.onSelectCustomManage(renameOpt?.label ?? null);
    expect(dialogs.showCustomNameDialog.value).toBe(true);
    dialogs.customNameDraft.value = "Renamed Provider";
    dialogs.applyCustomName();
    expect(store.state.provider.customProviders[0].name).toBe("Renamed Provider");
    expect(toasts.join("\n")).toContain("Renamed Provider");
    expect(dialogs.showCustomManage.value).toBe(true);

    const modelsOpt = dialogs.customManageOptions.value[2];
    dialogs.onSelectCustomManage(modelsOpt?.label ?? null);
    expect(dialogs.showCustomModelsDialog.value).toBe(true);
    dialogs.customModelsDraft.value = "model-b";
    dialogs.applyCustomModels();
    expect(store.state.provider.customProviders[0].models.map((m: any) => m.id)).toEqual(["model-b"]);
    expect(store.state.provider.activeModelByProvider.cp_test).toBe("model-b");
    expect(store.state.config.model).toBe("model-b");
    expect(dialogs.showCustomManage.value).toBe(true);
  });

  it("supports delete with confirmation and resets active provider", () => {
    const { store, toasts, dialogs } = createStoreWithCustomProvider();

    dialogs.openConnect();
    const customOpt = dialogs.providerOptions.value.find((o) => (o.keywords ?? []).includes("cp_test"));
    expect(customOpt).toBeTruthy();
    dialogs.onSelectProvider(customOpt!.label);
    expect(dialogs.showCustomManage.value).toBe(true);

    const deleteOpt = dialogs.customManageOptions.value[3];
    dialogs.onSelectCustomManage(deleteOpt?.label ?? null);
    expect(dialogs.showCustomDeleteConfirm.value).toBe(true);

    const confirmOpt = dialogs.customDeleteConfirmOptions.value[0];
    dialogs.onSelectCustomDeleteConfirm(confirmOpt?.label ?? null);

    expect(store.state.provider.customProviders.length).toBe(0);
    expect(String(store.state.provider.activeId ?? "")).toBe("");
    expect(String(store.state.config.model ?? "")).toBe("");
    expect(toasts.join("\n")).toContain("Custom provider deleted");
    expect(dialogs.showConnect.value).toBe(true);
  });

  it("falls back to another available provider after deleting the active custom provider", () => {
    const { store, dialogs } = createStoreWithCustomProvider();
    store.state.provider.connections.openai = { apiKey: "sk-openai" };
    store.state.provider.activeModelByProvider.openai = "gpt-5";

    dialogs.openConnect();
    const customOpt = dialogs.providerOptions.value.find((o) => (o.keywords ?? []).includes("cp_test"));
    dialogs.onSelectProvider(customOpt?.label ?? null);
    const deleteOpt = dialogs.customManageOptions.value[3];
    dialogs.onSelectCustomManage(deleteOpt?.label ?? null);
    const confirmOpt = dialogs.customDeleteConfirmOptions.value[0];
    dialogs.onSelectCustomDeleteConfirm(confirmOpt?.label ?? null);

    expect(String(store.state.provider.activeId ?? "")).toBe("openai");
    expect(String(store.state.config.model ?? "")).toBe("gpt-5");
  });
});
