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

/**
 * Validate the OpenClaw API key from the request header.
 * Returns a 401 NextResponse if invalid, or null if valid.
 */
export function validateOpenClawKey(request: NextRequest): NextResponse | null {
  const expectedKey = process.env.OPENCLAW_API_KEY;

  if (!expectedKey) {
    console.error('[OpenClaw] OPENCLAW_API_KEY is not set');
    return NextResponse.json({ error: 'OpenClaw API not configured' }, { status: 500 });
  }

  const providedKey = request.headers.get('x-openclaw-key');

  if (!providedKey || providedKey !== expectedKey) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  return null;
}
