import jwt from "jsonwebtoken";
import { User } from "../../models/User";

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const token = getCookie(event, "auth-token");

  if (!token) {
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized - No token provided",
    });
  }

  try {
    // Verify and decode the token
    const decoded = jwt.verify(token, config.jwtSecret as string) as any;

    // Get fresh user data from database
    const user = await User.findById(decoded.userId).select("-__v");

    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: "User not found",
      });
    }

    // Return user data (without sensitive fields)
    return {
      id: user._id,
      username: user.username,
      displayName: user.displayName,
      email: user.email,
      avatar: user.avatar,
      roles: user.roles,
      permissions: user.permissions,
      contributions: user.contributions,
    };
  } catch (error: any) {
    if (
      error.name === "JsonWebTokenError" ||
      error.name === "TokenExpiredError"
    ) {
      deleteCookie(event, "auth-token");
      throw createError({
        statusCode: 401,
        statusMessage: "Invalid or expired token",
      });
    }
    throw error;
  }
});
