const express = require('express');
const router = express.Router();
const { authenticateUser } = require('../middleware/auth');
const callService = require('../services/callService');

/**
 * POST /api/calls/initiate
 * Initiate a call
 */
router.post('/initiate', authenticateUser, async (req, res) => {
  try {
    const { conversationId, type, participants } = req.body;
    const userId = req.user.id;

    const call = await callService.initiateCall(
      userId,
      conversationId,
      type,
      participants || []
    );

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

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

/**
 * POST /api/calls/:callId/answer
 * Answer incoming call
 */
router.post('/:callId/answer', authenticateUser, async (req, res) => {
  try {
    const { callId } = req.params;
    const { accept } = req.body;
    const userId = req.user.id;

    const call = await callService.answerCall(callId, userId, accept);

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

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

/**
 * POST /api/calls/:callId/reject
 * Reject incoming call
 */
router.post('/:callId/reject', authenticateUser, async (req, res) => {
  try {
    const { callId } = req.params;
    const userId = req.user.id;

    const call = await callService.endCall(callId, userId, 'rejected');

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

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

/**
 * POST /api/calls/:callId/end
 * End active call
 */
router.post('/:callId/end', authenticateUser, async (req, res) => {
  try {
    const { callId } = req.params;
    const userId = req.user.id;

    const call = await callService.endCall(callId, userId, 'hangup');

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

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

/**
 * PATCH /api/calls/:callId/media
 * Update media state (mute/unmute, video on/off, screen share)
 */
router.patch('/:callId/media', authenticateUser, async (req, res) => {
  try {
    const { callId } = req.params;
    const mediaState = req.body;
    const userId = req.user.id;

    const updated = await callService.updateMediaState(
      callId,
      userId,
      mediaState
    );

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

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

/**
 * GET /api/calls/turn-credentials
 * Get TURN server credentials for NAT traversal
 */
router.get('/turn-credentials', authenticateUser, async (req, res) => {
  try {
    const userId = req.user.id;

    const credentials = await callService.generateTURNCredentials(userId);

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

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

/**
 * GET /api/calls/:callId
 * Get call details
 */
router.get('/:callId', authenticateUser, async (req, res) => {
  try {
    const { callId } = req.params;

    const call = await callService.getCall(callId);

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

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

module.exports = router;
