import { NextResponse, type NextRequest } from 'next/server';
import {
  isAllowedV3ReleasePath,
  isV3X402ReleaseEnabled,
} from './app/api/v3/x402/_lib/release';

/**
 * Release gate for x402 API routes.
 *
 * The checked-in registry is metadata only.  This deployment must not issue
 * payment challenges, accept payment payloads, or claim settlement until the
 * readiness gate has controlled evidence for request/resource binding, replay
 * protection, expiry/finality, and the configured payment rails.
 */
export function middleware(request: NextRequest): NextResponse {
  if (
    request.nextUrl.pathname.startsWith('/api/v3/') &&
    isV3X402ReleaseEnabled() &&
    isAllowedV3ReleasePath(request.nextUrl.pathname)
  ) {
    return NextResponse.next();
  }
  return NextResponse.json(
    {
      schema: 'vaultfire.v3.release-gate.v1',
      schemaVersion: '1.0.0',
      protocolVersion: '3.0.0',
      error: 'x402 payment routes are disabled pending release-readiness evidence',
      code: 'x402_release_gate_closed',
      retryable: false,
      releaseMode: 'disabled',
    },
    {
      status: 503,
      headers: {
        'Cache-Control': 'no-store',
        'X-Robots-Tag': 'noindex',
      },
    },
  );
}

export const config = {
  matcher: [
    '/api/x402/:path*',
    '/api/v3/:path*',
    '/sign/x402-test',
    '/sign/x402-pay',
    '/sign/x402-register',
  ],
};
