const { getEnv } = require("./envLoader");

exports.sendJwtToken = async (user, statuscode, res) => {
  const accessToken = user.generateAccessToken();
  const refreshToken = user.generateRefreshToken();
  user.refreshToken = [refreshToken];
  await user.save();

  // Parse expiry times from environment variables (assuming format like "7d", "24h", "30m")
  // Default fallbacks if not set
  const cookieExpireDays = parseInt(getEnv("COOKIE_EXPIRE") || process.env.COOKIE_EXPIRE) || 5;
  const cookieExpiry = new Date(Date.now() + cookieExpireDays * 24 * 60 * 60 * 1000);

  const options = {
    expires: cookieExpiry, // Fixed: 'expires' not 'expire'
    httpOnly: true,
    secure: (getEnv("NODE_ENV") || process.env.NODE_ENV) === 'production', // Only secure in production
  };

  // Create user object without sensitive data
  const userResponse = {
    _id: user._id,
    email: user.email,
    fullName: user.fullName,
    role: user.role,
    preferredLanguage: user.preferredLanguage || 'en',
    status: user.status,
    ownerType: user.ownerType, // Include ownerType in user response
    permissions: user.permissions, // Include permissions for frontend checks
  };

  res
    .status(statuscode)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .json({
      success: true,
      user: userResponse, // Return full user object
      accessToken: accessToken,
      refreshToken: refreshToken,
    });
};