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" });
  }

  await connectDB();

  // Find or create a test admin user (atomic to avoid race conditions in parallel tests)
  const member = await Member.findOneAndUpdate(
    { email: "test-admin@ghostguild.dev" },
    {
      $setOnInsert: {
        name: "Test Admin",
        circle: "founder",
        contributionAmount: 0,
        role: "admin",
        status: "active",
      },
    },
    { upsert: true, new: true },
  );

  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, "/admin", 302);
});
