import { Session } from './types';

// In-memory session store (use Redis in production)
const sessions = new Map<string, Session>();

const SESSION_DURATION = 10 * 60 * 1000; // 10 minutes in milliseconds

export function createSession(userId: string): string {
  const token = generateToken();
  const now = Date.now();

  // Remove any existing session for this user
  for (const [key, session] of sessions.entries()) {
    if (session.user_id === userId) {
      sessions.delete(key);
    }
  }

  sessions.set(token, {
    token,
    user_id: userId,
    created_at: now,
    expires_at: now + SESSION_DURATION
  });

  return token;
}

export function validateSession(token: string): Session | null {
  const session = sessions.get(token);

  if (!session) {
    return null;
  }

  // Check if session has expired
  if (Date.now() > session.expires_at) {
    sessions.delete(token);
    return null;
  }

  return session;
}

export function deleteSession(token: string): void {
  sessions.delete(token);
}

export function cleanupExpiredSessions(): void {
  const now = Date.now();
  for (const [token, session] of sessions.entries()) {
    if (now > session.expires_at) {
      sessions.delete(token);
    }
  }
}

function generateToken(): string {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`;
}

// Cleanup expired sessions every minute
setInterval(cleanupExpiredSessions, 60 * 1000);
