const invitationService = require('../services/invitationService');

/**
 * Invitation Controller
 * Handles invitation-related HTTP requests
 */

/**
 * Generate invitation code
 * POST /api/v1/invitations/generate
 */
const generateInvitationCode = async (req, res) => {
  try {
    const userId = req.user.userId;

    const user = await invitationService.generateInvitationCodeForUser(userId);

    return res.status(200).json({
      success: true,
      data: {
        invitationCode: user.invitationCode,
      },
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      error: {
        code: 'GENERATE_CODE_ERROR',
        message: 'Failed to generate invitation code',
        details: error.message,
      },
    });
  }
};

/**
 * Get invitation statistics
 * GET /api/v1/invitations/stats
 */
const getInvitationStats = async (req, res) => {
  try {
    const userId = req.user.userId;

    const stats = await invitationService.getInvitationStats(userId);

    return res.status(200).json({
      success: true,
      data: stats,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      error: {
        code: 'GET_STATS_ERROR',
        message: 'Failed to get invitation statistics',
        details: error.message,
      },
    });
  }
};

/**
 * Get invitation records
 * GET /api/v1/invitations/records
 */
const getInvitationRecords = async (req, res) => {
  try {
    const userId = req.user.userId;
    const { page, limit } = req.query;

    const result = await invitationService.getInvitationRecords(userId, {
      page,
      limit,
    });

    return res.status(200).json({
      success: true,
      data: result,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      error: {
        code: 'GET_RECORDS_ERROR',
        message: 'Failed to get invitation records',
        details: error.message,
      },
    });
  }
};

module.exports = {
  generateInvitationCode,
  getInvitationStats,
  getInvitationRecords,
};
