import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useConnectionStore } from "@/stores/connection.store";

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[]>([]);

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

  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;
  }

  /**
   * Connect to a server by connection ID.
   * Creates a new session tab and sets it active.
   *
   * TODO: Replace with Wails binding call — SSHService.Connect(hostname, port, ...)
   * For now, creates a mock session using the connection's name.
   */
  function connect(connectionId: number): void {
    const connectionStore = useConnectionStore();
    const conn = connectionStore.connections.find((c) => c.id === connectionId);
    if (!conn) return;

    // Check if there's already an active session for this connection
    const existing = sessions.value.find((s) => s.connectionId === connectionId);
    if (existing) {
      activeSessionId.value = existing.id;
      return;
    }

    // TODO: Replace with Wails binding call:
    //   const sessionId = await SSHService.Connect(conn.hostname, conn.port, username, authMethods, cols, rows)
    // For now, create a mock session
    addSession(connectionId, conn.name, conn.protocol);
  }

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