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

import { enforcePublicRateLimit, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { activateAccount } 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 activation token.
  const limited = await enforcePublicRateLimit(req, 'portalToken');
  if (limited) return limited;

  try {
    const { token, password } = await parseBody(req, bodySchema);
    await activateAccount(token, password);
    return NextResponse.json({ success: true });
  } catch (err) {
    return errorResponse(err);
  }
}
