/**
 * POST /api/invitations/bulk — Bulk create invitation codes.
 * Accepts a JSON array of invitation objects, proxies to Growth Service.
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as growthClient from '@/lib/growth-client';
export async function POST(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || !['super_admin', 'admin'].includes(caller.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const body = await req.json();
    if (!Array.isArray(body)) {
      return NextResponse.json({ error: 'Request body must be a JSON array' }, { status: 400 });
    }
    // Inject createdBy from the caller if not provided
    const enriched = body.map((item: Record<string, unknown>) => ({
      ...item,
      createdBy: item.createdBy || caller.id,
    }));
    const result = await growthClient.bulkCreateInvitations(enriched);
    const status = result.failed > 0 ? 207 : 201;
    return NextResponse.json(result, { status });
  } catch (error) {
    logError('Bulk invite error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
