const adminAuthService = require('../services/adminAuthService');
const logger = require('../config/logger');

/**
 * Admin Authentication Controller
 * Handles admin login requests
 */

/**
 * Admin login
 * POST /api/v1/admin/login
 */
const login = async (req, res) => {
  try {
    const { username, password } = req.body;

    // Validate input
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'MISSING_CREDENTIALS',
          message: 'Username and password are required',
        },
      });
    }

    // Extract login metadata
    const loginInfo = {
      ipAddress: req.ip || req.connection.remoteAddress,
      userAgent: req.headers['user-agent'],
      deviceInfo: {
        platform: req.headers['sec-ch-ua-platform'] || 'unknown',
        mobile: req.headers['sec-ch-ua-mobile'] === '?1',
      },
    };

    // Authenticate admin
    const result = await adminAuthService.loginAdmin(username, password, loginInfo);

    return res.status(200).json({
      success: true,
      data: result,
    });
  } catch (error) {
    logger.error('Admin login controller error:', error);

    // Handle specific errors
    if (error.message === 'Invalid username or password') {
      return res.status(401).json({
        success: false,
        error: {
          code: 'INVALID_CREDENTIALS',
          message: error.message,
        },
      });
    }

    if (error.message === 'Admin account is inactive') {
      return res.status(403).json({
        success: false,
        error: {
          code: 'ACCOUNT_INACTIVE',
          message: error.message,
        },
      });
    }

    return res.status(500).json({
      success: false,
      error: {
        code: 'LOGIN_ERROR',
        message: 'An error occurred during login',
        details: error.message,
      },
    });
  }
};

/**
 * Get current admin profile
 * GET /api/v1/admin/profile
 */
const getProfile = async (req, res) => {
  try {
    const admin = await adminAuthService.getAdminProfile(req.adminId);

    return res.status(200).json({
      success: true,
      data: { admin },
    });
  } catch (error) {
    logger.error('Get admin profile error:', error);

    return res.status(500).json({
      success: false,
      error: {
        code: 'PROFILE_ERROR',
        message: 'Failed to retrieve admin profile',
        details: error.message,
      },
    });
  }
};

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

    if (!token) {
      return res.status(400).json({
        success: false,
        error: {
          code: 'MISSING_TOKEN',
          message: 'Refresh token is required',
        },
      });
    }

    const result = await adminAuthService.refreshAdminToken(token);

    return res.status(200).json({
      success: true,
      data: result,
    });
  } catch (error) {
    logger.error('Admin refresh token error:', error);

    if (error.message === 'Token has expired' || error.message === 'Invalid token' || error.message === 'Invalid refresh token') {
      return res.status(401).json({
        success: false,
        error: {
          code: 'INVALID_TOKEN',
          message: 'Invalid or expired refresh token',
        },
      });
    }

    if (error.message === 'Admin not found' || error.message === 'Admin account is inactive') {
      return res.status(403).json({
        success: false,
        error: {
          code: 'ACCESS_DENIED',
          message: error.message,
        },
      });
    }

    return res.status(500).json({
      success: false,
      error: {
        code: 'REFRESH_ERROR',
        message: 'Failed to refresh token',
        details: error.message,
      },
    });
  }
};

module.exports = {
  login,
  getProfile,
  refreshToken,
};
