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

import { enforcePublicRateLimit } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { resetPassword } from '@/lib/services/portal-auth.service';

const bodySchema = z.object({
  token: z.string().min(1),
  password: z.string().min(9),
});

export async function POST(req: NextRequest): Promise<NextResponse> {
  // 10/hour/IP — bounds brute-force against the 32-byte reset token.
  const limited = await enforcePublicRateLimit(req, 'portalToken');
  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(parsed.error.issues[0]?.message ?? 'Invalid input');
    }

    await resetPassword(parsed.data.token, parsed.data.password);
    return NextResponse.json({ success: true });
  } catch (err) {
    return errorResponse(err);
  }
}
