import jwt from "jsonwebtoken";
import Member from "../../models/member.js";
import { connectDB } from "../../utils/mongoose.js";

export default defineEventHandler(async (event) => {
  // Only allow in development, unless explicitly enabled for Playwright preview runs
  if (
    process.env.NODE_ENV === "production" &&
    process.env.ALLOW_DEV_TEST_ENDPOINTS !== "true"
  ) {
    throw createError({ statusCode: 404, statusMessage: "Not found" });
  }

  const query = getQuery(event);
  const email = query.email;

  if (!email) {
    throw createError({
      statusCode: 400,
      statusMessage: "email query param required",
    });
  }

  await connectDB();

  const member = await Member.findOne({ email: email.toLowerCase() });

  if (!member) {
    throw createError({
      statusCode: 404,
      statusMessage: `No member found with email: ${email}`,
    });
  }

  const config = useRuntimeConfig(event);
  const token = jwt.sign(
    { memberId: member._id, email: member.email, tv: member.tokenVersion || 0 },
    config.jwtSecret,
    { expiresIn: "7d" },
  );

  setCookie(event, "auth-token", token, {
    httpOnly: true,
    secure: false,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });

  await sendRedirect(event, "/member/account", 302);
});
