import { NextResponse } from "next/server";
import { z } from "zod";
import { emailVerifySchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
const metadata = { requireAuth: false };
async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid request body" }, { status: 400 });
  }
  const parsed = emailVerifySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ ok: false, error: "Invalid token" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const customerTokenService = container.resolve("customerTokenService");
  const em = container.resolve("em");
  const result = await customerTokenService.verifyEmailToken(parsed.data.token, "email_verification");
  if (!result) {
    return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
  }
  await em.nativeUpdate(CustomerUser, { id: result.userId, tenantId: result.tenantId }, { emailVerifiedAt: /* @__PURE__ */ new Date() });
  void emitCustomerAccountsEvent("customer_accounts.email.verified", {
    userId: result.userId,
    recipientUserId: result.userId,
    tenantId: result.tenantId
  }).catch(() => void 0);
  return NextResponse.json({ ok: true });
}
const successSchema = z.object({ ok: z.literal(true) });
const errorSchema = z.object({ ok: z.literal(false), error: z.string() });
const methodDoc = {
  summary: "Verify customer email address",
  description: "Validates the email verification token and marks the email as verified.",
  tags: ["Customer Authentication"],
  requestBody: {
    schema: emailVerifySchema,
    description: "Email verification token."
  },
  responses: [
    { status: 200, description: "Email verified", schema: successSchema }
  ],
  errors: [
    { status: 400, description: "Invalid or expired token", schema: errorSchema }
  ]
};
const openApi = {
  summary: "Verify customer email",
  description: "Handles email verification for customer accounts.",
  methods: { POST: methodDoc }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=verify.js.map
