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

import { errorResponse } from '@/lib/errors';
import { consumeCrmInvite } from '@/lib/services/crm-invite.service';
import { enforcePublicRateLimit, parseBody } from '@/lib/api/route-helpers';

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 CRM invite token.
  const limited = await enforcePublicRateLimit(req, 'portalToken');
  if (limited) return limited;

  try {
    const { token, password } = await parseBody(req, bodySchema);
    const result = await consumeCrmInvite({ token, password });
    return NextResponse.json({ data: { email: result.email } });
  } catch (err) {
    return errorResponse(err);
  }
}
