/**
 * POST /api/x402/trust/email-verify
 *
 * x402 payment-gated x402-Email verification — $0.01 USDC per call.
 *
 * Same input/output shape as the free public verifier at
 * /api/x402/email/verify, but discoverable in the Coinbase x402 Bazaar
 * and includes a signed receipt block (`_x402.paid: true`) so a paying
 * caller can prove they paid for the lookup.
 *
 * The FREE public verifier remains at /api/x402/email/verify — recipient
 * mail servers / spam filters should keep using it (they can't pay per
 * inbound message). This paid lane is for batch / programmatic callers
 * who want bazaar discovery + audit trail.
 *
 * Proxies internally to the free verifier so there is exactly one
 * implementation of the verification logic.
 */

import { NextRequest, NextResponse } from 'next/server';
import { withX402 } from 'x402-next';
import { facilitator } from '@coinbase/x402';

const PAY_TO = '0xfA15Ee28939B222B0448261A22156070f0A7813C';

const handler = async (req: NextRequest) => {
  // Read the JSON body once; if it's missing/invalid, the inner verifier
  // will return verified:false with a reason — we don't reject here.
  let body: unknown = null;
  try {
    body = await req.json();
  } catch {
    body = {};
  }

  try {
    const innerUrl = `${req.nextUrl.origin}/api/x402/email/verify`;
    const innerRes = await fetch(innerUrl, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(body),
      cache: 'no-store',
    });
    const data = await innerRes.json();

    return NextResponse.json(
      {
        ...data,
        _x402: {
          paid: true,
          price: '$0.01 USDC',
          service: 'vaultfire-x402-email',
          facilitator: 'cdp',
          specVersion: '0.1.0',
        },
      },
      {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Cache-Control': 'no-store',
        },
      },
    );
  } catch {
    return NextResponse.json(
      { error: 'Failed to reach internal x402-email verifier' },
      { status: 502 },
    );
  }
};

// Canonical CDP paywall (matches actions/* family) — triggers CDP catalog auto-ingest.
export const POST = withX402(handler, PAY_TO, {
  price: '$0.01', network: 'base',
  config: {
    description:
      'x402-Email Spec v0.1 verifier (paid lane). Validates a sender address, accountability bond, and x402 payment header from an inbound email and returns a routing recommendation (inbox | review | spam). Same input as the free public endpoint at /api/x402/email/verify; this lane adds a signed _x402 receipt for bazaar callers. Live on Base mainnet.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object',
          properties: {
            from: { type: 'string', description: 'Sender wallet address (0x...) or VNS name' },
            paymentTx: { type: 'string', description: 'Optional x402 payment tx hash' },
            messageId: { type: 'string', description: 'Optional inbound email Message-ID' },
          },
        },
      },
      output: {
        type: 'object',
        properties: {
          specVersion: { type: 'string' },
          verified: { type: 'boolean' },
          sender: { type: 'object' },
          bond: { type: 'object' },
          payment: { type: 'object' },
          recommendation: { type: 'string', enum: ['inbox', 'review', 'spam'] },
          reasons: { type: 'array', items: { type: 'string' } },
          claimUrl: { type: 'string' },
          specUrl: { type: 'string' },
          tookMs: { type: 'number' },
        },
      },
    },
  },
}, facilitator);

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' } });
}
