const fs = require('node:fs');
const path = require('node:path');

const root = path.resolve(__dirname, '..');
const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8');

describe('x402 release-surface safety gate', () => {
  const directRoutes = [
    'app/api/x402/verify/route.ts',
    'app/api/x402/settle/route.ts',
    'app/api/x402/submit-signed/route.ts',
    'app/app/api/x402/verify/route.ts',
    'app/app/api/x402/settle/route.ts',
  ];

  test.each(directRoutes)('%s is closed before it parses a caller payload', (route) => {
    const source = read(route);
    expect(source).toContain("import { x402ReleaseGateClosed } from '../_lib/release-gate';");
    expect(source.indexOf('return x402ReleaseGateClosed();')).toBeGreaterThan(-1);
    expect(source.indexOf('return x402ReleaseGateClosed();')).toBeLessThan(source.indexOf('await req.json()'));
  });

  test('middleware closes every Vercel-facing x402 API route with a non-cacheable 503', () => {
    const source = read('middleware.ts');
    expect(source).toContain("matcher: ['/api/x402/:path*']");
    expect(source).toContain('x402_release_gate_closed');
    expect(source).toContain('status: 503');
    expect(source).toContain("'Cache-Control': 'no-store'");
  });

  test('trust helper cannot fabricate a Base or Solana payTo and fails closed before parsing headers', () => {
    const source = read('app/api/x402/trust/_lib/verify-payment.ts');
    expect(source).toContain("process.env.PAY_TO_ADDRESS?.trim() ?? ''");
    expect(source).not.toContain('PAY_TO_SOL ||');
    expect(source).not.toContain('6KpXaFmaR8WPWr79qzsMBvwDbDzYFErwNoWxfwqDr8JU');
    expect(source.indexOf('return { valid: false, response: x402ReleaseGateClosed() };')).toBeLessThan(source.indexOf('const paymentHeader'));
  });

  test('legacy helper defense-in-depth requires Base resource binding, validAfter, and a confirmed settlement', () => {
    const source = read('app/api/x402/trust/_lib/verify-payment.ts');
    expect(source).toContain("paymentPayload.network !== 'base' || resource !== req.nextUrl.toString()");
    expect(source).toContain('Number(auth.validAfter) > now || Number(auth.validBefore) < now');
    expect(source).toContain("await publicClient.waitForTransactionReceipt({ hash: txHash, timeout: 30_000 })");
    expect(source).not.toContain('payment accepted on signature');
    expect(source).not.toContain("txHash: 'self-payment'");
  });

  test('public discovery contains no payable route, recipient, Solana rail, or live facilitator assertion', () => {
    const discovery = JSON.parse(read('public/.well-known/x402.json'));
    expect(discovery.releaseStatus).toBe('disabled_pending_readiness_evidence');
    expect(discovery.endpoints).toEqual([]);
    expect(discovery.networks).toEqual([]);
    expect(discovery.accepts).toEqual([]);
    expect(discovery.payTo).toBeUndefined();
    expect(discovery.payToSolana).toBeUndefined();
  });

  test('public webhook writes require an explicit operator token and do not accept body-address ownership', () => {
    for (const route of ['app/api/agent/webhooks/route.ts', 'app/app/api/agent/webhooks/route.ts']) {
      const source = read(route);
      expect(source).toContain('WEBHOOK_ADMIN_TOKEN');
      expect(source).toContain('webhook_auth_unconfigured');
      expect(source.match(/const authorizationFailure = requireWebhookWriteAuthorization\(req\);/g)).toHaveLength(3);
      expect(source).not.toContain('agentAddress is required');
    }
  });

  test('cron writes fail closed without authentication or persistence health', () => {
    const source = read('app/api/cron/heartbeat/route.ts');
    expect(source).toContain("if (!cronSecret)");
    expect(source).toContain("status: 503, headers: { 'Cache-Control': 'no-store' }");
    expect(source).toContain("error: 'heartbeat persistence write/read failed'");
  });
});
