import type { SessionInfo, SessionState } from './types.js'

const sessions = new Map<string, SessionInfo>()
const listeners = new Set<() => void>()

export function registerSession(id: string, cwd: string, branch?: string): void {
  sessions.set(id, {
    id,
    cwd,
    branch,
    state: 'idle',
    lastActivity: Date.now(),
    pendingApprovals: 0,
  })
  notify()
}

export function unregisterSession(id: string): void {
  sessions.delete(id)
  notify()
}

export function updateSessionState(id: string, state: SessionState): void {
  const session = sessions.get(id)
  if (session) {
    session.state = state
    session.lastActivity = Date.now()
    notify()
  }
}

export function updatePendingApprovals(id: string, count: number): void {
  const session = sessions.get(id)
  if (session) {
    session.pendingApprovals = count
    notify()
  }
}

export function getSessions(): SessionInfo[] {
  return Array.from(sessions.values()).sort((a, b) => b.lastActivity - a.lastActivity)
}

export function getSession(id: string): SessionInfo | undefined {
  return sessions.get(id)
}

export function onSessionsChange(listener: () => void): () => void {
  listeners.add(listener)
  return () => listeners.delete(listener)
}

function notify(): void {
  for (const listener of listeners) {
    listener()
  }
}
