const express = require('express');
const { logToFile } = require('../mariadb');
const { validateSession, deleteSession } = require('../sessionModel');
const router = express.Router();

// Simple session validation endpoint
router.post('/validate', async (req, res) => {
  try {
    const { sessionId } = req.body;
    
    if (!sessionId) {
      logToFile('SESSION: Validate missing sessionId');
      return res.status(400).json({ error: 'sessionId required' });
    }
    
    const session = await validateSession(sessionId);
    if (!session || !session.data || !session.data.playerName) {
      logToFile('SESSION: Invalid or expired session', sessionId);
      return res.status(401).json({ error: 'Invalid or expired session' });
    }
    
    const playerName = session.data.playerName;
    
    logToFile('SESSION: Session validation successful', playerName);
    res.json({ 
      valid: true, 
      playerName
    });
  } catch (error) {
    console.error('Session validation error:', error);
    logToFile('SESSION: Failed to validate session', error);
    res.status(500).json({ error: String(error) });
  }
});

// Logout endpoint
router.post('/logout', async (req, res) => {
  try {
    const { sessionId } = req.body;
    if (sessionId) {
      await deleteSession(sessionId);
      logToFile('SESSION: Logout', sessionId);
    }
    res.json({ success: true });
  } catch (error) {
    logToFile('SESSION: Logout error', error);
    res.status(500).json({ error: String(error) });
  }
});

console.log('Session routes registered');
module.exports = router;
