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

import { enforcePublicRateLimit } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
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> {
  // 3/hour/IP - tightest of the portal limiters because each successful
  // call sends an outbound email and timing differences here are the
  // primary email-enumeration vector.
  const limited = await enforcePublicRateLimit(req, 'portalForgot');
  if (limited) return limited;

  try {
    let body: unknown;
    try {
      body = await req.json();
    } catch {
      throw new ValidationError('Invalid request body');
    }

    const parsed = bodySchema.safeParse(body);
    if (!parsed.success) throw new ValidationError('Invalid email address');

    // 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 });
  } catch (error) {
    return errorResponse(error);
  }
}
