import { Request, Response } from 'express';
import { sendSuccess, sendError } from '../../utils/response';
import { revokeRefreshToken } from '../../utils/jwt';
import { ErrorCode } from '@saferoute/constants';
import * as authService from './service';

export async function sendOtp(req: Request, res: Response): Promise<void> {
  try {
    const { phone } = req.body;
    const result = await authService.sendOtpToPhone(phone);
    sendSuccess(res, result, 'OTP sent successfully');
  } catch (error: any) {
    if (error.message === 'RATE_LIMIT_EXCEEDED') {
      sendError(res, ErrorCode.RATE_LIMIT_EXCEEDED, 'Too many OTP requests. Please try again later.');
    } else {
      sendError(res, ErrorCode.SERVER_ERROR, 'Failed to send OTP.');
    }
  }
}

export async function verifyOtpHandler(req: Request, res: Response): Promise<void> {
  try {
    const { phone, otp } = req.body;
    const result = await authService.verifyOtpAndLogin(phone, otp);
    sendSuccess(res, result, 'OTP verified');
  } catch (error: any) {
    if (error.message === 'AUTH_INVALID_OTP') {
      sendError(res, ErrorCode.AUTH_INVALID_OTP, 'Invalid or expired OTP. Please try again.');
    } else if (error.message === 'ACCOUNT_DEACTIVATED') {
      sendError(res, ErrorCode.ACCESS_DENIED, 'Your account has been deactivated. Please contact support.');
    } else {
      sendError(res, ErrorCode.SERVER_ERROR, 'Authentication failed.');
    }
  }
}

export async function logout(req: Request, res: Response): Promise<void> {
  try {
    const { refreshToken } = req.body;
    if (refreshToken) {
      await revokeRefreshToken(refreshToken);
    }
    sendSuccess(res, null, 'Logged out successfully');
  } catch (error) {
    sendError(res, ErrorCode.SERVER_ERROR, 'Logout failed.');
  }
}

export async function refreshToken(req: Request, res: Response): Promise<void> {
  try {
    const { refreshToken: token } = req.body;
    const result = await authService.refreshAccessToken(token);
    sendSuccess(res, result, 'Token refreshed successfully');
  } catch (error: any) {
    if (error.message === 'AUTH_TOKEN_EXPIRED') {
      sendError(res, ErrorCode.AUTH_TOKEN_EXPIRED, 'Refresh token is invalid or expired. Please login again.');
    } else {
      sendError(res, ErrorCode.SERVER_ERROR, 'Token refresh failed.');
    }
  }
}

export async function getMe(req: Request, res: Response): Promise<void> {
  try {
    const userId = req.user!.userId;
    const user = await authService.getCurrentUser(userId);
    sendSuccess(res, user, 'Profile retrieved successfully');
  } catch (error: any) {
    if (error.message === 'RESOURCE_NOT_FOUND') {
      sendError(res, ErrorCode.RESOURCE_NOT_FOUND, 'User not found.');
    } else {
      sendError(res, ErrorCode.SERVER_ERROR, 'Failed to retrieve profile.');
    }
  }
}
