import Update from "../../models/update.js";

export default defineEventHandler(async (event) => {
  let memberId = null
  try {
    const member = await requireAuth(event)
    memberId = member._id.toString()
  } catch {
    // Not authenticated — continue with public-only access
  }

  const query = getQuery(event);
  const limit = parseInt(query.limit) || 20;
  const skip = parseInt(query.skip) || 0;

  try {
    // Build privacy filter
    let privacyFilter;
    if (!memberId) {
      // Not authenticated - only show public updates
      privacyFilter = { privacy: "public" };
    } else {
      // Authenticated member - show public and members-only updates
      privacyFilter = { privacy: { $in: ["public", "members"] } };
    }

    const updates = await Update.find(privacyFilter)
      .populate("author", "name avatar")
      .sort({ createdAt: -1 })
      .limit(limit)
      .skip(skip);

    const total = await Update.countDocuments(privacyFilter);

    return {
      updates,
      total,
      hasMore: skip + limit < total,
    };
  } catch (error) {
    console.error("Get updates error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch updates",
    });
  }
});
