/**
 * PATCH /api/invitations/[id] — Update invitation code (disable/enable).
 * DELETE /api/invitations/[id] — Delete 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';
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || !['super_admin', 'admin'].includes(caller.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const { id } = await params;
    const body = await req.json();
    const updates: Record<string, unknown> = {};
    if (body.status && ['active', 'disabled'].includes(body.status)) {
      updates.status = body.status;
    }
    if (typeof body.maxUses === 'number') {
      updates.maxUses = Math.max(1, body.maxUses);
    }
    if (body.description !== undefined) {
      updates.description = body.description;
    }
    if (body.expiresAt !== undefined) {
      updates.expiresAt = body.expiresAt;
    }
    const updated = await growthClient.updateInvitation(id, updates);
    if (!updated) {
      return NextResponse.json({ error: 'Update failed' }, { status: 500 });
    }
    return NextResponse.json(updated);
  } catch (error) {
    logError('Update invitation error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || caller.role !== 'super_admin') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const { id } = await params;
    await growthClient.deleteInvitation(id);
    return NextResponse.json({ success: true });
  } catch (error) {
    logError('Delete invitation error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
