import Admin from "../models/Admin.js";
import logger from "../utils/logger.js";
import jwt from "jsonwebtoken";

/**
 * Generate JWT Token
 */
const generateToken = (adminId) => {
  return jwt.sign({ id: adminId }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE || "7d",
  });
};

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

    // Validate input
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        error: "Email and password are required",
      });
    }

    // Get allowed admin email from environment
    const allowedAdminEmail = process.env.ADMIN_EMAIL || "admin@samaa.com";
    const normalizedEmail = email.toLowerCase();

    // Check if email matches the allowed admin email
    if (normalizedEmail !== allowedAdminEmail.toLowerCase()) {
      logger.warn("Login attempt with unauthorized email", {
        email: normalizedEmail,
      });
      return res.status(401).json({
        success: false,
        error: "Invalid email or password",
      });
    }

    // Find admin and include password field
    const admin = await Admin.findOne({ email: normalizedEmail }).select(
      "+password"
    );

    // Check if admin exists
    if (!admin) {
      logger.warn("Login attempt - admin not found", {
        email: normalizedEmail,
      });
      return res.status(401).json({
        success: false,
        error: "Invalid email or password",
      });
    }

    // Check if admin is active
    if (!admin.isActive) {
      logger.warn("Login attempt for inactive admin", { email });
      return res.status(403).json({
        success: false,
        error: "Your account has been deactivated",
      });
    }

    // Verify password
    const isPasswordValid = await admin.comparePassword(password);

    if (!isPasswordValid) {
      logger.warn("Login attempt with invalid password", { email });
      return res.status(401).json({
        success: false,
        error: "Invalid email or password",
      });
    }

    // Update last login
    admin.lastLogin = new Date();
    await admin.save({ validateBeforeSave: false });

    // Generate token
    const token = generateToken(admin._id);

    // Remove password from response
    const adminData = admin.toJSON();

    logger.info("Admin logged in successfully", {
      email: admin.email,
    });

    // Send response
    res.status(200).json({
      success: true,
      message: "Login successful",
      data: {
        admin: adminData,
        token,
      },
    });
  } catch (error) {
    logger.error("Login error", error);
    next(error);
  }
};

/**
 * Get Current Admin Profile
 * GET /api/auth/me
 */
export const getMe = async (req, res, next) => {
  try {
    const admin = await Admin.findById(req.admin.id);

    if (!admin) {
      return res.status(404).json({
        success: false,
        error: "Admin not found",
      });
    }

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

/**
 * Logout (client-side token removal, but we can track it)
 * POST /api/auth/logout
 */
export const logout = async (req, res, next) => {
  try {
    logger.info("Admin logged out", {
      email: req.admin?.email,
    });

    res.status(200).json({
      success: true,
      message: "Logout successful",
    });
  } catch (error) {
    logger.error("Logout error", error);
    next(error);
  }
};
