import { NextResponse } from "next/server";
import { z } from "zod";
import { magicLinkRequestSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
import {
  resolveTenantContext,
  TenantResolutionError
} from "@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { rateLimitErrorSchema } from "@open-mercato/shared/lib/ratelimit/helpers";
import {
  checkAuthRateLimit,
  customerMagicLinkRateLimitConfig,
  customerMagicLinkIpRateLimitConfig
} from "@open-mercato/core/modules/customer_accounts/lib/rateLimiter";
import { readNormalizedEmailFromJsonRequest } from "@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier";
const metadata = { requireAuth: false };
async function POST(req) {
  const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req);
  const { error: rateLimitError } = await checkAuthRateLimit({
    req,
    ipConfig: customerMagicLinkIpRateLimitConfig,
    compoundConfig: customerMagicLinkRateLimitConfig,
    compoundIdentifier: rateLimitEmail
  });
  if (rateLimitError) return rateLimitError;
  let body;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ ok: true });
  }
  const parsed = magicLinkRequestSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ ok: true });
  }
  const { email } = parsed.data;
  let tenantId;
  try {
    const context = await resolveTenantContext(req, parsed.data.tenantId);
    tenantId = context.tenantId;
  } catch (err) {
    if (err instanceof TenantResolutionError) {
      return NextResponse.json({ ok: true });
    }
    throw err;
  }
  const container = await createRequestContainer();
  const customerUserService = container.resolve("customerUserService");
  const customerTokenService = container.resolve("customerTokenService");
  const user = await customerUserService.findByEmail(email, tenantId);
  if (user) {
    await customerTokenService.createMagicLink(user.id, tenantId);
    void import("@open-mercato/core/modules/customer_accounts/events").then(
      ({ emitCustomerAccountsEvent }) => emitCustomerAccountsEvent("customer_accounts.magic_link.requested", {
        userId: user.id,
        tenantId,
        organizationId: user.organizationId
      })
    ).catch(() => void 0);
  }
  return NextResponse.json({ ok: true });
}
const successSchema = z.object({ ok: z.literal(true) });
const methodDoc = {
  summary: "Request magic link login",
  description: "Sends a magic link to the customer email. Always returns 200 to prevent enumeration.",
  tags: ["Customer Authentication"],
  requestBody: {
    schema: magicLinkRequestSchema,
    description: "Magic link request with email."
  },
  responses: [
    { status: 200, description: "Request accepted", schema: successSchema }
  ],
  errors: [
    { status: 429, description: "Too many requests", schema: rateLimitErrorSchema }
  ]
};
const openApi = {
  summary: "Request customer magic link",
  description: "Handles magic link login requests for customer accounts.",
  methods: { POST: methodDoc }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=request.js.map
