const adminAuthService = require("../../services/admin/adminAuthService");
const ApiResponse = require("../../utils/apiResponse");
const { asyncHandler } = require("../../middleware/errorHandler");

exports.login = asyncHandler(async (req, res) => {
  const { email, password, twoFactorCode } = req.body;
  const ip = req.ip || req.connection.remoteAddress;
  const device = req.headers['user-agent'];

  const result = await adminAuthService.login(email, password, ip, device, twoFactorCode);

  if (result.requires2FA) {
    return ApiResponse.success(res, { requires2FA: true, message: 'Please enter your 2FA code', type: result.type });
  }

  ApiResponse.success(res, {
    admin: result.admin,
    accessToken: result.accessToken,
    refreshToken: result.refreshToken,
  }, 'Login successful');
});

exports.verify2fa = asyncHandler(async (req, res) => {
  const { email, code } = req.body;
  const ip = req.ip || req.connection.remoteAddress;
  const device = req.headers['user-agent'];
  console.log('Verify 2FA Request:', req.body);
  const result = await adminAuthService.verify2fa(email,code, ip, device);

  ApiResponse.success(res, {
    user: result.user,
    accessToken: result.accessToken,
    refreshToken: result.refreshToken,
  }, 'Login successful');
});

exports.resendVerification = asyncHandler(async (req, res) => {
  const { email } = req.body;
   const ip = req.ip || req.connection.remoteAddress;
  const device = req.headers['user-agent'];
  await adminAuthService.resend2fa(email, ip, device);
  ApiResponse.success(res, null, 'Two factor code sent');
});

exports.refreshToken = asyncHandler(async (req, res) => {
  const { refreshToken } = req.body;
  const result = await adminAuthService.refreshToken(refreshToken);
  ApiResponse.success(res, result, 'Token refreshed');
});

exports.register = asyncHandler(async (req, res) => {
  const data = await adminAuthService.register(req.body);
  ApiResponse.success(res, data, "Logged in successfully");
});


exports.me = asyncHandler(async (req, res) => {
  const data = await adminAuthService.me(req.admin?.id);
  ApiResponse.success(res, data);
});
