const { sessionHelpers, logToFile } = require('./mariadb');

async function createSession(sessionId, data, expiresAt) {
  try {
    // Check if session already exists
    const existing = await sessionHelpers.get(sessionId);
    if (existing) {
      await sessionHelpers.update(sessionId, data);
      return existing;
    }
    await sessionHelpers.create(sessionId, data, expiresAt);
    logToFile('Session created:', sessionId);
  } catch (error) {
    console.error('Error creating session:', error);
    logToFile('Session creation error:', error);
    throw error;
  }
}

async function validateSession(sessionId) {
  try {
    const session = await sessionHelpers.get(sessionId);
    if (!session) return null;
    
    // Check expiration
    if (session.expires_at && new Date(session.expires_at) < new Date()) {
      await sessionHelpers.delete(sessionId);
      logToFile('Session expired:', sessionId);
      return null;
    }
    
    return session;
  } catch (error) {
    console.error('Error validating session:', error);
    logToFile('Session validation error:', error);
    return null;
  }
}

async function deleteSession(sessionId) {
  try {
    await sessionHelpers.delete(sessionId);
    logToFile('Session deleted:', sessionId);
  } catch (error) {
    console.error('Error deleting session:', error);
    logToFile('Session deletion error:', error);
  }
}

module.exports = {
  createSession,
  validateSession,
  deleteSession
};
