import { NextRequest, NextResponse } from 'next/server';
import { ethers } from 'ethers';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { withFailover } from '../../_lib/rpc-retry';

/**
 * GET /api/agent/vouching
 *
 * Query a vouch profile by agent address from the VaultfireReputationStaking contract.
 *
 * Query params:
 *   ?address=0x...    — (required) agent address to look up
 *   ?chain=base       — chain to query (default: "base")
 *
 * Returns:
 *   totalVouchesReceived, totalStakeReceived, totalVouchesGiven, totalStakeGiven, slashCount
 */

const CONTRACTS: Record<string, string> = {
  base:      '0xd42BBfD3061A38D4B5540317A31D90212380069b',
  avalanche: '0x32211773C8266774A704aeD471f8eF073f34bA79',
  arbitrum:  '0x9d4AbeAa8201e6f1649c296dd179Bbb3c401f96F',
  polygon:   '0x3ceA2B0853B76Ac75603C1fa2A29D96A4467Bb79',
};

const ABI = [
  {
    name: 'getProfile',
    type: 'function',
    stateMutability: 'view',
    inputs: [{ name: 'agent', type: 'address' }],
    outputs: [
      { name: 'totalVouchesReceived', type: 'uint256' },
      { name: 'totalStakeReceived',   type: 'uint256' },
      { name: 'totalVouchesGiven',    type: 'uint256' },
      { name: 'totalStakeGiven',      type: 'uint256' },
      { name: 'slashCount',           type: 'uint256' },
    ],
  },
];

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const chain = resolveChain(searchParams.get('chain'));
    const address = searchParams.get('address');

    if (!address) {
      return NextResponse.json({ error: 'Missing required query param: address' }, { status: 400 });
    }

    if (!ethers.isAddress(address)) {
      return NextResponse.json({ error: 'Invalid wallet address' }, { status: 400 });
    }

    if (!chain) {
      return NextResponse.json(
        { error: `Unsupported chain. Use one of: ${SUPPORTED_CHAINS.join(', ')} (or chain IDs: 8453, 43114, 42161, 137)` },
        { status: 400 },
      );
    }
    const contractAddress = CONTRACTS[chain];

    const profile = await withFailover(chain, async (provider) => {
      const contract = new ethers.Contract(contractAddress, ABI, provider);
      return contract.getProfile(address);
    });

    return NextResponse.json({
      address,
      chain,
      contract: contractAddress,
      profile: {
        totalVouchesReceived: profile.totalVouchesReceived.toString(),
        totalStakeReceived:   profile.totalStakeReceived.toString(),
        totalVouchesGiven:    profile.totalVouchesGiven.toString(),
        totalStakeGiven:      profile.totalStakeGiven.toString(),
        slashCount:           profile.slashCount.toString(),
      },
    });
  } catch (error: unknown) {
    // VF-N05/VF-14: Never leak raw error messages to clients — log server-side only
    console.error('[vouching] Unhandled error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
