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

import { errorResponse, ValidationError } from '@/lib/errors';
import { consumeCrmInvite } from '@/lib/services/crm-invite.service';
import { enforcePublicRateLimit } 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 {
    let body: unknown;
    try {
      body = await req.json();
    } catch {
      // Use {error} via errorResponse so the envelope matches every other
      // route (auditor-F §32 — was emitting {message} as a third variant).
      throw new ValidationError('Invalid request body');
    }

    const parsed = bodySchema.safeParse(body);
    if (!parsed.success) {
      throw new ValidationError(parsed.error.issues[0]?.message ?? 'Invalid input');
    }

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