// server/utils/sessionStore.ts
// Lightweight in-memory session store with automatic cleanup

interface SessionData {
  user: any;
  accessToken: string;
  idToken: string;
  refreshToken: string;
  expiresAt: number;
  createdAt: number;
  scope?: string;
  status?: string;
}

// In-memory session storage
const sessions = new Map<string, SessionData>();

// Cleanup expired sessions every 5 minutes
setInterval(() => {
  const now = Date.now();
  let cleanedCount = 0;
  
  for (const [sessionId, session] of sessions.entries()) {
    if (session.expiresAt < now) {
      sessions.delete(sessionId);
      cleanedCount++;
    }
  }
  
  if (cleanedCount > 0) {
    console.log(`🧹 Cleaned up ${cleanedCount} expired sessions. Active sessions: ${sessions.size}`);
  }
}, 5 * 60 * 1000); // Every 5 minutes

export function createSession(data: SessionData): string {
  // Generate random session ID
  const sessionId = Array.from({ length: 32 }, () => 
    Math.floor(Math.random() * 16).toString(16)
  ).join('');
  
  sessions.set(sessionId, data);
  console.log(`✅ Session created: ${sessionId.substring(0, 8)}... (Total active: ${sessions.size})`);
  
  return sessionId;
}

export function getSession(sessionId: string): SessionData | null {
  const session = sessions.get(sessionId);
  
  if (!session) {
    return null;
  }
  
  // Check if expired
  if (session.expiresAt < Date.now()) {
    sessions.delete(sessionId);
    return null;
  }
  
  return session;
}

export function deleteSession(sessionId: string): void {
  sessions.delete(sessionId);
  console.log(`🗑️ Session deleted: ${sessionId.substring(0, 8)}... (Remaining: ${sessions.size})`);
}

export function updateSession(sessionId: string, updates: Partial<SessionData>): boolean {
  const session = sessions.get(sessionId);
  if (!session) {
    return false;
  }
  
  // Update the session with new data
  const updatedSession = {
    ...session,
    ...updates,
  };
  
  sessions.set(sessionId, updatedSession);
  return true;
}

// Helper function to get session from cookie (for API handlers)
export async function getSessionFromCookie(event: any): Promise<SessionData | null> {
  const { getCookie } = await import('h3');
  const sessionId = getCookie(event, 'user_session');
  
  if (!sessionId) {
    return null;
  }
  
  return getSession(sessionId);
}

// Get session stats
export function getSessionStats() {
  return {
    totalSessions: sessions.size,
    sessions: Array.from(sessions.entries()).map(([id, session]) => ({
      id: id.substring(0, 8) + '...',
      user: session.user?.email || session.user?.name,
      expiresAt: new Date(session.expiresAt).toISOString(),
      isExpired: session.expiresAt < Date.now()
    }))
  };
}
