import { defineStore } from "pinia";
import { ref, computed } from "vue";

export interface Session {
  id: string;
  connectionId: number;
  name: string;
  protocol: "ssh" | "rdp";
  active: boolean;
}

/**
 * Session store.
 * Manages active sessions and tab order.
 *
 * Sessions are populated by the Go SessionManager once plugins are wired up.
 * For now, mock sessions are used to render the tab bar.
 */
export const useSessionStore = defineStore("session", () => {
  const sessions = ref<Session[]>([
    { id: "s1", connectionId: 1, name: "Asgard", protocol: "ssh", active: true },
    { id: "s2", connectionId: 2, name: "Docker", protocol: "ssh", active: false },
    { id: "s3", connectionId: 4, name: "CLT-VMHOST01", protocol: "rdp", active: false },
  ]);

  const activeSessionId = ref<string | null>("s1");

  const activeSession = computed(() =>
    sessions.value.find((s) => s.id === activeSessionId.value) ?? null,
  );

  const sessionCount = computed(() => sessions.value.length);

  /** Switch to a session tab. */
  function activateSession(id: string): void {
    activeSessionId.value = id;
  }

  /** Close a session tab. */
  function closeSession(id: string): void {
    const idx = sessions.value.findIndex((s) => s.id === id);
    if (idx === -1) return;

    sessions.value.splice(idx, 1);

    // If we closed the active session, activate an adjacent one
    if (activeSessionId.value === id) {
      if (sessions.value.length === 0) {
        activeSessionId.value = null;
      } else {
        const nextIdx = Math.min(idx, sessions.value.length - 1);
        activeSessionId.value = sessions.value[nextIdx].id;
      }
    }
  }

  /** Add a new session (placeholder — will be called from connection double-click). */
  function addSession(connectionId: number, name: string, protocol: "ssh" | "rdp"): void {
    const id = `s${Date.now()}`;
    sessions.value.push({ id, connectionId, name, protocol, active: false });
    activeSessionId.value = id;
  }

  return {
    sessions,
    activeSessionId,
    activeSession,
    sessionCount,
    activateSession,
    closeSession,
    addSession,
  };
});
