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

import { errorResponse } from '@/lib/errors';
import { consumeCrmInvite } from '@/lib/services/crm-invite.service';

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

export async function POST(req: NextRequest): Promise<NextResponse> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ message: 'Invalid request body' }, { status: 400 });
  }

  const parsed = bodySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { message: parsed.error.errors[0]?.message ?? 'Invalid input' },
      { status: 400 },
    );
  }

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