/**
 * /api/agent/premium  —  ERC-8128 tier-gated premium endpoint.
 *
 * GET  : Self-describing — documents the route, no signature required.
 * POST : ERC-8128 signed request required. Gold+ Street Cred tier only.
 *
 * Verifies an inbound RFC 9421 HTTP signature with keyid
 *   erc8128:8453:<address>
 * resolves the agent's canonical Street Cred score by calling
 * VaultfireStreetCred.computeScore() on Base mainnet, then returns
 * a premium payload (full score breakdown, bond profile, insurance
 * eligibility) ONLY if tier ≥ Gold.
 *
 * Sprint: 4 (April 2026) — first end-to-end ERC-8128 deployment in production.
 * Spec  : https://ethereum-magicians.org/t/erc-8128-signed-http-requests-with-ethereum/
 */

import { NextRequest, NextResponse } from 'next/server';
import { verifyAndResolve, TIER, TIER_NAMES, STREET_CRED_ADDRESS, VAULTFIRE_CHAIN_ID } from '../../_lib/erc8128';
import { checkRateLimit, RATE_LIMIT_GET } from '../../../lib/rate-limit';

// Force Node.js runtime (not Edge) — ethers v6 + @slicekit/erc8128 need Node
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const CORS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Signature, Signature-Input, Content-Digest',
  'Access-Control-Expose-Headers': 'WWW-Authenticate',
};

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: CORS });
}

/* ─────────────────────────────── GET ─────────────────────────────── */

export async function GET(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_GET);
  if (rl) return rl;

  return NextResponse.json(
    {
      route: '/api/agent/premium',
      method: 'POST',
      auth: {
        scheme: 'ERC-8128',
        spec: 'https://ethereum-magicians.org/t/erc-8128-signed-http-requests-with-ethereum/',
        rfc: 'https://datatracker.ietf.org/doc/rfc9421/',
        keyidFormat: `erc8128:${VAULTFIRE_CHAIN_ID}:<address>`,
        chainId: VAULTFIRE_CHAIN_ID,
        chainName: 'Base',
      },
      requirements: {
        minTier: TIER_NAMES[TIER.GOLD],
        minTierValue: TIER.GOLD,
        scoreSource: STREET_CRED_ADDRESS,
        scoreFunction: 'VaultfireStreetCred.computeScore(address)',
      },
      requiredHeaders: ['Signature', 'Signature-Input', 'Content-Digest (for POST with body)'],
      sdk: {
        package: '@vaultfire/agent-sdk',
        version: '>=0.6.0',
        helper: 'signedFetch(url, init, signer)',
      },
      description:
        'Premium endpoint for Gold+ tier Vaultfire agents. Returns full Street Cred breakdown, bond profile, and insurance eligibility. Requires a valid ERC-8128 signed HTTP request.',
      errorCodes: {
        unsigned: '401 — Missing Signature/Signature-Input headers',
        invalid_signature: '401 — Signature failed verification (tampered, expired, replay, or wrong address)',
        insufficient_tier: '403 — Agent below Gold tier',
      },
    },
    { headers: CORS }
  );
}

/* ─────────────────────────────── POST ─────────────────────────────── */

export async function POST(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_GET);
  if (rl) return rl;

  let result: Awaited<ReturnType<typeof verifyAndResolve>>;
  try {
    result = await verifyAndResolve(request, { minTier: TIER.GOLD });
  } catch (e) {
    // Defensive: any unexpected throw (RPC failure, malformed request, etc.)
    // returns a clean 500 instead of an empty Vercel error page.
    console.error('[/api/agent/premium] verify_threw:', e);
    return NextResponse.json(
      {
        error: 'verify_failed',
        reason: 'Verification could not complete — try again or check Signature/Signature-Input headers',
      },
      { status: 500, headers: CORS }
    );
  }

  if (!result.ok) {
    const headers: Record<string, string> = { ...CORS };
    if (result.error.code === 'unsigned' || result.error.code === 'invalid_signature') {
      headers['WWW-Authenticate'] = `ERC-8128 chain="${VAULTFIRE_CHAIN_ID}", realm="vaultfire-premium"`;
    }
    return NextResponse.json(
      {
        error: result.error.code,
        reason: result.error.reason,
        ...('detail' in result.error && result.error.detail ? { detail: result.error.detail } : {}),
        ...('required' in result.error
          ? {
              required: { tier: result.error.required, tierName: TIER_NAMES[result.error.required] },
              actual: { tier: result.error.actual, tierName: TIER_NAMES[result.error.actual] },
              agent: {
                // Convert BigInt stakeWei to string — JSON.stringify can't handle BigInt natively
                ...result.error.agent,
                stakeWei: result.error.agent.stakeWei.toString(),
              },
            }
          : {}),
      },
      { status: result.error.status, headers }
    );
  }

  const { agent } = result;
  const { trust } = agent;

  // Premium payload — only delivered to verified Gold+ signers
  return NextResponse.json(
    {
      ok: true,
      tier: 'premium',
      verifiedAt: new Date().toISOString(),
      agent: {
        address: agent.address,
        chainId: agent.chainId,
        keyid: agent.keyid,
      },
      streetCred: {
        score: trust.score,
        tier: trust.tier,
        tierName: trust.tierName,
        registered: trust.registered,
        hasBond: trust.hasBond,
        bondActive: trust.bondActive,
        bondCount: trust.bondCount,
        stake: {
          wei: trust.stakeWei.toString(),
          eth: trust.stakeEth,
        },
        scoreSource: STREET_CRED_ADDRESS,
        scoreFunction: 'VaultfireStreetCred.computeScore(address)',
      },
      premium: {
        // Premium-only data: full insurance eligibility profile
        insuranceEligible: trust.bondActive && trust.score >= 56,
        rateLimitMultiplier: trust.tier === TIER.PLATINUM ? 10 : trust.tier === TIER.GOLD ? 5 : 1,
        priorityRouting: true,
        attestationWeight: trust.score, // higher tier = higher vouch weight
        capabilities: [
          'priority_routing',
          'higher_rate_limits',
          'insurance_claims',
          'attestation_signing',
          ...(trust.tier === TIER.PLATINUM ? ['governance_voting', 'oracle_feeds'] : []),
        ],
      },
    },
    { headers: CORS }
  );
}
