// server/utils/sessionStore.ts
// Simple in-memory session store (for development)
// In production, use Redis or a database

import { getCookie } from 'h3'
import { randomBytes } from 'crypto'

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

const sessions = new Map<string, SessionData>();

// Clean up expired sessions every 5 minutes
setInterval(() => {
    const now = Date.now();
    for (const [sessionId, session] of sessions.entries()) {
        if (session.expiresAt < now) {
            sessions.delete(sessionId);
        }
    }
}, 5 * 60 * 1000);

export function createSession(data: SessionData): string {
    // Generate a secure random session ID
    const sessionId = randomBytes(32).toString('hex');
    sessions.set(sessionId, data);
    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);
}

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

