import { NextRequest, NextResponse } from 'next/server';
import { completeSetupAction } from '@/lib/setup/wizard-actions';
import type { CompleteSetupInput } from '@/lib/setup/wizard-actions';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json() as CompleteSetupInput;

    // Basic server-side validation
    if (!body.licenseKey || !body.adminUsername || !body.adminPassword || !body.appName) {
      return NextResponse.json({ success: false, error: 'Missing required fields' }, { status: 400 });
    }

    // Attach client IP for EULA audit trail
    const clientIp =
      request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
      request.headers.get('x-real-ip') ??
      'unknown';

    const result = await completeSetupAction({ ...body, clientIp });
    if (!result.success) {
      return NextResponse.json(result, { status: 422 });
    }

    return NextResponse.json(result);
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Setup failed';
    return NextResponse.json({ success: false, error: message }, { status: 500 });
  }
}
