const db = require('../database/db');

/**
 * Authenticate requests from Nexus Engine
 * Verifies Nexus API key and player identity
 */
module.exports = async function nexusAuth(req, res, next) {
  try {
    const apiKey = req.headers['x-nexus-api-key'];
    const nexusPlayerId = req.headers['x-nexus-player-id'];

    if (!apiKey || !nexusPlayerId) {
      return res.status(401).json({
        success: false,
        error: 'Missing Nexus authentication headers'
      });
    }

    // Verify API key
    if (apiKey !== process.env.NEXUS_API_KEY) {
      return res.status(401).json({
        success: false,
        error: 'Invalid Nexus API key'
      });
    }

    // Find user by Nexus player ID
    const userResult = await db.query(
      `SELECT u.* 
       FROM users u
       JOIN game_sessions gs ON gs.user_id = u.id
       WHERE gs.nexus_player_id = $1
       ORDER BY gs.started_at DESC
       LIMIT 1`,
      [nexusPlayerId]
    );

    if (userResult.rows.length === 0) {
      // Try to find by identities table
      const identityResult = await db.query(
        `SELECT u.* 
         FROM users u
         JOIN identities i ON i.user_id = u.id
         WHERE i.identifier = $1 OR i.identifier LIKE $2`,
        [nexusPlayerId, `%${nexusPlayerId}%`]
      );

      if (identityResult.rows.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Player not found'
        });
      }

      req.nexusUser = identityResult.rows[0];
    } else {
      req.nexusUser = userResult.rows[0];
    }

    next();

  } catch (error) {
    console.error('Nexus auth error:', error);
    res.status(500).json({
      success: false,
      error: 'Authentication failed'
    });
  }
};
