const express = require('express');
const router = express.Router();
const { authenticateUser: auth } = require('../middleware/auth');
const nexusAuth = require('../middleware/nexusAuth');
const nexusService = require('../services/nexusIntegration');

/**
 * POST /api/nexus/sessions/start
 * Start game session
 */
router.post('/sessions/start', nexusAuth, async (req, res) => {
  try {
    const { nexusPlayerId, gameId, gameName, metadata } = req.body;
    const userId = req.nexusUser.id;

    const result = await nexusService.startGameSession(
      userId,
      nexusPlayerId,
      gameId,
      gameName,
      metadata
    );

    res.json({
      success: true,
      session: result.session,
      overlayConfig: result.overlayConfig
    });

  } catch (error) {
    console.error('Failed to start session:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/sessions/:id/update
 * Update game session state
 */
router.post('/sessions/:id/update', nexusAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const { state, metadata } = req.body;
    const userId = req.nexusUser.id;

    const result = await nexusService.updateGameSession(
      id,
      userId,
      state,
      metadata
    );

    res.json({
      success: true,
      session: result
    });

  } catch (error) {
    console.error('Failed to update session:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/sessions/:id/end
 * End game session
 */
router.post('/sessions/:id/end', nexusAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const { duration, metadata } = req.body;
    const userId = req.nexusUser.id;

    const result = await nexusService.endGameSession(
      id,
      userId,
      metadata
    );

    res.json({
      success: true,
      session: result
    });

  } catch (error) {
    console.error('Failed to end session:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/lobbies
 * Create game lobby
 */
router.post('/lobbies', auth, async (req, res) => {
  try {
    const { gameId, maxPlayers = 8, isPublic = false } = req.body;
    const userId = req.user.id;

    const lobby = await nexusService.createGameLobby(
      userId,
      gameId,
      maxPlayers,
      isPublic
    );

    res.json({
      success: true,
      lobby
    });

  } catch (error) {
    console.error('Failed to create lobby:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/lobbies/:id/join
 * Join game lobby
 */
router.post('/lobbies/:id/join', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { lobbyCode } = req.body;
    const userId = req.user.id;

    const result = await nexusService.joinGameLobby(
      id,
      userId,
      lobbyCode
    );

    res.json({
      success: true,
      lobby: result
    });

  } catch (error) {
    console.error('Failed to join lobby:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/lobbies/:id/ready
 * Toggle ready status
 */
router.post('/lobbies/:id/ready', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const ready = await nexusService.toggleReady(id, userId);

    res.json({
      success: true,
      ready
    });

  } catch (error) {
    console.error('Failed to toggle ready:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/lobbies/:id/start
 * Start game (host only)
 */
router.post('/lobbies/:id/start', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const result = await nexusService.startLobbyGame(id, userId);

    res.json({
      success: true,
      lobby: result
    });

  } catch (error) {
    console.error('Failed to start lobby:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/nexus/lobbies/:id/leave
 * Leave lobby
 */
router.post('/lobbies/:id/leave', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    await nexusService.leaveLobby(id, userId);

    res.json({
      success: true
    });

  } catch (error) {
    console.error('Failed to leave lobby:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/friends
 * Get all friends with status
 */
router.get('/friends', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const result = await nexusService.getFriends(userId);

    res.json({
      success: true,
      ...result
    });

  } catch (error) {
    console.error('Failed to get friends:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/friends/requests
 * Get pending friend requests
 */
router.get('/friends/requests', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const requests = await nexusService.getPendingFriendRequests(userId);

    res.json({
      success: true,
      requests
    });

  } catch (error) {
    console.error('Failed to get friend requests:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/friends/request
 * Send friend request
 */
router.post('/friends/request', auth, async (req, res) => {
  try {
    const { targetIdentifier } = req.body;
    const userId = req.user.id;

    if (!targetIdentifier) {
      return res.status(400).json({
        success: false,
        error: 'targetIdentifier is required'
      });
    }

    const request = await nexusService.sendFriendRequest(
      userId,
      targetIdentifier
    );

    res.json({
      success: true,
      friendRequest: {
        id: request.id,
        toUserId: request.to_user_id,
        status: request.status,
        createdAt: request.created_at
      }
    });

  } catch (error) {
    console.error('Failed to send friend request:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/friends/requests/:id/respond
 * Respond to friend request
 */
router.post('/friends/requests/:id/respond', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { accept } = req.body;
    const userId = req.user.id;

    const result = await nexusService.respondToFriendRequest(
      id,
      userId,
      accept
    );

    res.json({
      success: true,
      ...result
    });

  } catch (error) {
    console.error('Failed to respond to friend request:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * DELETE /api/friends/:userId
 * Remove friend
 */
router.delete('/friends/:userId', auth, async (req, res) => {
  try {
    const { userId: friendUserId } = req.params;
    const userId = req.user.id;

    await nexusService.removeFriend(userId, friendUserId);

    res.json({
      success: true
    });

  } catch (error) {
    console.error('Failed to remove friend:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;
