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

export default defineEventHandler(async (event) => {
  const userId = getRouterParam(event, "id");
  let currentMemberId = null
  try {
    const member = await requireAuth(event)
    currentMemberId = 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 {
    // Verify the user exists
    const user = await Member.findById(userId);
    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: "User not found",
      });
    }

    // Build privacy filter
    let privacyFilter;
    if (!currentMemberId) {
      // Not authenticated - only show public updates
      privacyFilter = { author: userId, privacy: "public" };
    } else if (currentMemberId === userId) {
      // Viewing own updates - show all
      privacyFilter = { author: userId };
    } else {
      // Authenticated member viewing another's updates - show public and members-only
      privacyFilter = { author: userId, 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,
      user: {
        _id: user._id,
        name: user.name,
        avatar: user.avatar,
      },
    };
  } catch (error) {
    if (error.statusCode) throw error;
    console.error("Get user updates error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to fetch user updates",
    });
  }
});
