const authService = require('../services/authService');
const { validationResult } = require('express-validator');
const { sendSuccess, sendError } = require('../utils/response');

/**
 * Authentication Controller
 * Handles authentication-related HTTP requests
 */

/**
 * WeChat Login
 * POST /api/v1/auth/wechat-login
 */
const wechatLogin = async (req, res) => {
  try {
    // Validate request
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        message: 'Invalid input data',
        data: null,
        errors: errors.array(),
      });
    }

    const { code, userInfo, invitationCode } = req.body;

    // Extract device info from request
    const deviceInfo = {
      ipAddress: req.ip || req.connection.remoteAddress,
      userAgent: req.headers['user-agent'],
      device: req.body.deviceInfo || {},
    };

    // Authenticate with WeChat
    const result = await authService.wechatLogin(
      code,
      userInfo,
      invitationCode,
      deviceInfo
    );

    return sendSuccess(res, {
      user: {
        id: result.user.id,
        nickname: result.user.nickname,
        avatar: result.user.avatar,
        language: result.user.language,
        balance: result.user.balance,
        invitationCode: result.user.invitationCode,
        status: result.user.status,
      },
      token: result.accessToken,
      refreshToken: result.refreshToken,
    }, 'Login successful');
  } catch (error) {
    return sendError(res, error.message || 'Login failed', 500, 500);
  }
};

/**
 * Refresh Token
 * POST /api/v1/auth/refresh-token
 */
const refreshToken = async (req, res) => {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return sendError(res, 'Refresh token is required', 400, 400);
    }

    // Refresh access token
    const result = await authService.refreshAccessToken(refreshToken);

    return sendSuccess(res, {
      token: result.accessToken,
      refreshToken: result.refreshToken,
      user: {
        id: result.user.id,
        nickname: result.user.nickname,
        avatar: result.user.avatar,
        language: result.user.language,
        balance: result.user.balance,
        status: result.user.status,
      },
    }, 'Token refreshed successfully');
  } catch (error) {
    return sendError(res, error.message || 'Token refresh failed', 401, 401);
  }
};

/**
 * Logout
 * POST /api/v1/auth/logout
 */
const logout = async (req, res) => {
  try {
    // In a stateless JWT system, logout is handled client-side
    // by removing the token. We just acknowledge the request.
    // If using token blacklist, add token to blacklist here.

    return sendSuccess(res, null, 'Logged out successfully');
  } catch (error) {
    return sendError(res, error.message || 'Logout failed', 500, 500);
  }
};

module.exports = {
  wechatLogin,
  refreshToken,
  logout,
};
