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/insurance
 *
 * Query the VaultfireBondInsurancePool contract.
 *
 * Query params:
 *   ?address=0x...    — (optional) contributor address; omit to fetch pool-level stats
 *   ?chain=base       — chain to query (default: "base")
 *
 * With address:    Returns contributor profile.
 * Without address: Returns pool stats (balance, contributorCount, claimCount, paidOut).
 */

const CONTRACTS: Record<string, string> = {
  base:      '0xa074e372d5221b605E9762e41B86EbdBEBF1a978',
  avalanche: '0xf7B2dC73Ec69528F171F4a0ded62da557866BaA5',
  arbitrum:  '0xAca6fe18917a985F6741FB986461B976e2A0a5DB',
  polygon:   '0x9CF1fcba0c657e9FD807a9c8c028E0ef561b6B56',
};

const ABI = [
  {
    name: 'getPoolStats',
    type: 'function',
    stateMutability: 'view',
    inputs: [],
    outputs: [
      { name: 'balance',          type: 'uint256' },
      { name: 'contributorCount', type: 'uint256' },
      { name: 'claimCount',       type: 'uint256' },
      { name: 'paidOut',          type: 'uint256' },
    ],
  },
  {
    name: 'getContributorProfile',
    type: 'function',
    stateMutability: 'view',
    inputs: [{ name: 'contributor', type: 'address' }],
    outputs: [
      { name: 'totalContributed', type: 'uint256' },
      { name: 'activeStake',      type: 'uint256' },
      { name: 'claimsAgainst',    type: 'uint256' },
      { name: 'claimsPaid',       type: 'uint256' },
      { name: 'joinedAt',         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 (!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];

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

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

      return NextResponse.json({
        address,
        chain,
        contract: contractAddress,
        contributorProfile: {
          totalContributed: cp.totalContributed.toString(),
          activeStake:      cp.activeStake.toString(),
          claimsAgainst:    cp.claimsAgainst.toString(),
          claimsPaid:       cp.claimsPaid.toString(),
          joinedAt:         cp.joinedAt.toString(),
        },
      });
    }

    // Pool-level stats
    const stats = await withFailover(chain, async (provider) => {
      const contract = new ethers.Contract(contractAddress, ABI, provider);
      return contract.getPoolStats();
    });

    return NextResponse.json({
      chain,
      contract: contractAddress,
      poolStats: {
        balance:          stats.balance.toString(),
        contributorCount: stats.contributorCount.toString(),
        claimCount:       stats.claimCount.toString(),
        paidOut:          stats.paidOut.toString(),
      },
    });
  } catch (error: any) {
    console.error('[insurance] Internal error:', error instanceof Error ? error.message : error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
