/**
 * Authentication Controller
 * Handles user authentication operations
 */

const jwt = require("jsonwebtoken");
const User = require("../models/User");
const ActivityLog = require("../models/ActivityLog");
const config = require("../config/config");

/**
 * User Login
 * POST /api/auth/login
 */
const login = async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // Find user by username or email
    let user = await User.findByUsername(username);

    if (!user) {
      user = await User.findByEmail(username);
    }

    if (!user) {
      return res.status(401).json({
        success: false,
        message: "Invalid credentials",
      });
    }

    // Check if user is active
    if (!user.is_active) {
      return res.status(401).json({
        success: false,
        message: "Account is deactivated. Please contact administrator.",
      });
    }

    // Verify password
    const isValidPassword = await User.verifyPassword(password, user.password);

    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: "Invalid credentials",
      });
    }

    // Generate JWT token
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn },
    );

    // Update last login
    await User.updateLastLogin(user.id);

    // Log activity
    await ActivityLog.create({
      userId: user.id,
      actionType: "LOGIN",
      entityType: "User",
      entityId: user.id,
      description: `User ${user.username} logged in`,
      ipAddress: req.ip,
      userAgent: req.headers["user-agent"],
    });

    // Send response
    res.json({
      success: true,
      message: "Login successful",
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          role: user.role,
          firstName: user.first_name,
          lastName: user.last_name,
          employeeId: user.employee_id,
          departmentName: user.department_name,
        },
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get Current User Profile
 * GET /api/auth/profile
 */
const getProfile = async (req, res, next) => {
  try {
    const user = await User.findById(req.user.id);

    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found",
      });
    }

    res.json({
      success: true,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        firstName: user.first_name,
        lastName: user.last_name,
        employeeCode: user.emp_code,
        departmentId: user.department_id,
        departmentName: user.department_name,
        lastLogin: user.last_login,
      },
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Change Password
 * POST /api/auth/change-password
 */
const changePassword = async (req, res, next) => {
  try {
    const { currentPassword, newPassword } = req.body;

    // Get current user
    const user = await User.findById(req.user.id);

    // Verify current password
    const isValidPassword = await User.verifyPassword(
      currentPassword,
      user.password,
    );

    if (!isValidPassword) {
      return res.status(400).json({
        success: false,
        message: "Current password is incorrect",
      });
    }

    // Update password
    await User.changePassword(req.user.id, newPassword);

    // Log activity
    await ActivityLog.create({
      userId: req.user.id,
      actionType: "PASSWORD_CHANGE",
      entityType: "User",
      entityId: req.user.id,
      description: "Password changed successfully",
      ipAddress: req.ip,
      userAgent: req.headers["user-agent"],
    });

    res.json({
      success: true,
      message: "Password changed successfully",
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Logout
 * POST /api/auth/logout
 */
const logout = async (req, res, next) => {
  try {
    // Log activity
    await ActivityLog.create({
      userId: req.user.id,
      actionType: "LOGOUT",
      entityType: "User",
      entityId: req.user.id,
      description: `User ${req.user.username} logged out`,
      ipAddress: req.ip,
      userAgent: req.headers["user-agent"],
    });

    res.json({
      success: true,
      message: "Logged out successfully",
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Refresh Token
 * POST /api/auth/refresh-token
 */
const refreshToken = async (req, res, next) => {
  try {
    // Generate new token
    const token = jwt.sign(
      { userId: req.user.id, role: req.user.role },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn },
    );

    res.json({
      success: true,
      data: { token },
    });
  } catch (error) {
    next(error);
  }
};

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