import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

import { logger } from '@/lib/logger';
import { requestPasswordReset } from '@/lib/services/portal-auth.service';

const bodySchema = z.object({ email: z.string().email() });

export async function POST(req: NextRequest): Promise<NextResponse> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
  }

  const parsed = bodySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: 'Invalid email address' }, { status: 400 });
  }

  // Always return 200 to prevent account-enumeration. Errors are logged
  // server-side, never surfaced to the client.
  try {
    await requestPasswordReset(parsed.data.email);
  } catch (err) {
    logger.error({ err }, 'Portal forgot-password failed (swallowed)');
  }
  return NextResponse.json({ success: true });
}
