import Member from "../../models/member.js";
import { requireAuth } from "../../utils/auth.js";

export default defineEventHandler(async (event) => {
  await requireAuth(event);

  const id = event.context.params.id;

  try {
    const member = await Member.findOne({
      _id: id,
      showInDirectory: true,
      status: "active",
    })
      .select(
        "name pronouns timeZone avatar studio bio location socialLinks circle craftTags board createdAt memberNumber",
      )
      .lean();

    if (!member) {
      throw createError({
        statusCode: 404,
        message: "Member not found",
      });
    }

    const filtered = {
      _id: member._id,
      name: member.name,
      circle: member.circle,
      createdAt: member.createdAt,
      memberNumber: member.memberNumber,
      avatar: member.avatar,
      pronouns: member.pronouns,
      timeZone: member.timeZone,
      studio: member.studio,
      bio: member.bio,
      location: member.location,
      socialLinks: member.socialLinks,
      craftTags: member.craftTags,
      board: {
        slackHandle: member.board?.slackHandle,
      },
    };

    return { member: filtered };
  } catch (error) {
    if (error.statusCode) {
      throw error;
    }
    console.error("Member profile fetch error:", error);
    throw createError({
      statusCode: 500,
      message: "Failed to fetch member profile",
    });
  }
});
