/**
 * GET /api/invitations — List all invitation codes.
 * POST /api/invitations — Create a new invitation code.
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as growthClient from '@/lib/growth-client';
import crypto from 'crypto';
export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const url = new URL(req.url);
    const limit = parseInt(url.searchParams.get('limit') ?? '100', 10);
    const offset = parseInt(url.searchParams.get('offset') ?? '0', 10);
    const [listRes, countRes] = await Promise.all([
      growthClient.listInvitations(limit, offset),
      growthClient.countInvitations(),
    ]);
    const codes = listRes.invitations;
    const total = countRes.count;
    return NextResponse.json({ codes, total });
  } catch (error) {
    logError('List invitations error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
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();
    const {
      description = '',
      grantPlan = 'pro',
      grantTrialDays = 0,
      bonusTokens = 0,
      maxUses = 100,
      expiresAt = null,
      code: customCode,
    } = body;
    if (!['pro', 'enterprise'].includes(grantPlan)) {
      return NextResponse.json({ error: 'grantPlan must be pro or enterprise' }, { status: 400 });
    }
    const code = customCode
      ? customCode.toUpperCase().replace(/[^A-Z0-9-]/g, '')
      : `INVITE-${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
    const invitation = await growthClient.createInvitation({
      code,
      description,
      createdBy: caller.id,
      grantPlan,
      grantTrialDays: Math.max(0, grantTrialDays),
      bonusTokens: Math.max(0, bonusTokens),
      maxUses: Math.max(1, maxUses),
      expiresAt,
    });
    return NextResponse.json(invitation, { status: 201 });
  } catch (error) {
    logError('Create invitation error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
