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

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

  const query = getQuery(event);
  const search = query.search || "";
  const circle = query.circle || "";
  const craftTag = query.craftTag || "";

  const dbQuery = {
    showInDirectory: true,
    status: "active",
  };

  if (circle) {
    dbQuery.circle = circle;
  }

  const andConditions = [];

  if (search) {
    const escaped = escapeRegex(search);
    andConditions.push({
      $or: [
        { name: { $regex: escaped, $options: "i" } },
        { bio: { $regex: escaped, $options: "i" } },
      ],
    });
  }

  if (craftTag) {
    dbQuery.craftTags = craftTag;
  }

  if (andConditions.length > 0) {
    dbQuery.$and = andConditions;
  }

  try {
    const members = await Member.find(dbQuery)
      .select(
        "name pronouns timeZone avatar studio bio location socialLinks circle craftTags board createdAt",
      )
      .sort({ createdAt: -1 })
      .lean();

    const filteredMembers = members.map((member) => ({
      _id: member._id,
      name: member.name,
      circle: member.circle,
      createdAt: member.createdAt,
      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,
      },
    }));

    const [craftTags, cooperativeTags] = await Promise.all([
      Tag.find({ pool: "craft", active: true }).sort({ label: 1 }).lean(),
      Tag.find({ pool: "cooperative", active: true }).sort({ label: 1 }).lean(),
    ]);

    return {
      members: filteredMembers,
      totalCount: filteredMembers.length,
      filters: {
        craftTags: craftTags.map((t) => ({ slug: t.slug, label: t.label })),
        cooperativeTags: cooperativeTags.map((t) => ({
          slug: t.slug,
          label: t.label,
        })),
      },
    };
  } catch (error) {
    if (error.statusCode) throw error;
    console.error("Directory fetch error:", error);
    throw createError({
      statusCode: 500,
      message: "Failed to fetch member directory",
    });
  }
});
