import { NextResponse } from "next/server";
import { z } from "zod";
import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { passwordChangeSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
const metadata = { requireAuth: false };
async function POST(req) {
  const auth = await getCustomerAuthFromRequest(req);
  if (!auth) {
    return NextResponse.json({ ok: false, error: "Authentication required" }, { status: 401 });
  }
  let body;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid request body" }, { status: 400 });
  }
  const parsed = passwordChangeSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ ok: false, error: "Validation failed" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const customerUserService = container.resolve("customerUserService");
  const customerSessionService = container.resolve("customerSessionService");
  const em = container.resolve("em");
  const user = await customerUserService.findById(auth.sub, auth.tenantId);
  if (!user) {
    return NextResponse.json({ ok: false, error: "User not found" }, { status: 404 });
  }
  const currentValid = await customerUserService.verifyPassword(user, parsed.data.currentPassword);
  if (!currentValid) {
    return NextResponse.json({ ok: false, error: "Current password is incorrect" }, { status: 400 });
  }
  await em.transactional(async (trx) => {
    await customerUserService.updatePassword(user, parsed.data.newPassword, trx);
    await customerSessionService.revokeAllUserSessions(user.id, trx);
  });
  void emitCustomerAccountsEvent("customer_accounts.password.changed", {
    userId: user.id,
    tenantId: auth.tenantId,
    organizationId: auth.orgId ?? null,
    changedBy: "self",
    changedById: null,
    at: (/* @__PURE__ */ new Date()).toISOString()
  }).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: "Change customer password",
  description: "Changes the authenticated customer user password after verifying the current password. Revokes all existing sessions.",
  tags: ["Customer Portal"],
  requestBody: { schema: passwordChangeSchema },
  responses: [{ status: 200, description: "Password changed", schema: successSchema }],
  errors: [
    { status: 400, description: "Current password incorrect or validation failed", schema: errorSchema },
    { status: 401, description: "Not authenticated", schema: errorSchema }
  ]
};
const openApi = {
  summary: "Change customer password",
  methods: { POST: methodDoc }
};
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=password-change.js.map
