import { reactive } from "vue";
import { describe, expect, it } from "vitest";
import { useSessionsDialog } from "../src/dimsdk/pages/utils/sessions.ts";

describe("dimsdk session switch confirm", () => {
  it("prompts when switching sessions while busy, then interrupts and switches on confirm", async () => {
    let interrupted = false;
    const store: any = {
      state: reactive({
        sessionId: "s1",
        context: { cwd: "/work" },
        messages: [],
        revertedMessages: [],
        runningAgentRound: true,
        paused: null,
        approval: { active: null },
      }),
      interrupt() {
        interrupted = true;
      },
    };

    const calls: any[] = [];
    const sessionsApi: any = {
      async list() {
        return [
          { id: "s1", updatedAt: 1, title: "s1", summary: "", messageCount: 0 },
          { id: "s2", updatedAt: 2, title: "s2", summary: "", messageCount: 0 },
        ];
      },
      async use(id: string) {
        calls.push(["use", id]);
      },
      async createNew() {
        calls.push(["new"]);
      },
      async delete() {},
    };

    const sessions = useSessionsDialog({ store, sessionsApi });
    await sessions.openSessionsDialog();
    sessions.sessionsIndex.value = sessions.sessionsList.value.findIndex((session) => session.id === "s2");

    await sessions.openSelectedSession();
    expect(sessions.showSwitchConfirm.value).toBe(true);
    expect(calls.length).toBe(0);

    await sessions.confirmSwitch();
    expect(interrupted).toBe(true);
    expect(calls).toEqual([["use", "s2"]]);
    expect(sessions.showSwitchConfirm.value).toBe(false);
    expect(sessions.showSessions.value).toBe(false);
  });

  it("runs the deferred after callback only after confirm", async () => {
    const store: any = {
      state: reactive({
        sessionId: "s1",
        context: { cwd: "/work" },
        messages: [],
        revertedMessages: [],
        runningAgentRound: true,
        paused: null,
        approval: { active: null },
      }),
      interrupt() {},
    };

    const calls: any[] = [];
    const sessionsApi: any = {
      async list() {
        return [{ id: "s1", updatedAt: 1, title: "s1", summary: "", messageCount: 0 }];
      },
      async use() {},
      async createNew() {
        calls.push(["new"]);
      },
      async delete() {},
    };

    let afterCalled = false;
    const sessions = useSessionsDialog({
      store,
      sessionsApi,
    });
    await sessions.createNewSession({
      after: () => {
        afterCalled = true;
      },
    });
    expect(calls.length).toBe(0);
    expect(afterCalled).toBe(false);
    expect(sessions.showSwitchConfirm.value).toBe(true);

    await sessions.confirmSwitch();
    expect(calls).toEqual([["new"]]);
    expect(afterCalled).toBe(true);
  });
});
