import { createRoute } from "../../modules/api-utils/createRoute";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { prisma } from "../../constants";

/* GET /v1/cw/members */
export default createRoute(
  "get",
  ["/members"],
  async (c) => {
    const activeOnly = c.req.query("active") !== "false";

    const dbMembers = await prisma.cwMember.findMany({
      where: activeOnly ? { inactiveFlag: false } : undefined,
      orderBy: [{ firstName: "asc" }, { lastName: "asc" }],
    });

    const members = dbMembers.map((m) => ({
      id: m.cwMemberId,
      identifier: m.identifier,
      firstName: m.firstName,
      lastName: m.lastName,
      name: `${m.firstName} ${m.lastName}`.trim(),
      officeEmail: m.officeEmail,
      inactive: m.inactiveFlag,
    }));

    const response = apiResponse.successful(
      "CW members fetched successfully!",
      members
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware()
);
