import { Router } from 'express';
import { prisma } from '../db.js';
import { toCentsBigInt, centsJson } from '../cents.js';

const router = Router();

router.get('/', async (_req, res) => {
  try {
    const users = await prisma.user.findMany({
      where: { role: 'user' },
      include: {
        inventory: {
          include: { item: true },
        },
      },
    });

    const ranked = users
      .map((u) => {
        const inventoryValue = u.inventory.reduce(
          (sum, inv) => sum + toCentsBigInt(inv.valueCents),
          0n
        );
        const balance = toCentsBigInt(u.balance);
        const totalWealth = balance + inventoryValue;
        return {
          id: u.id,
          username: u.username,
          avatarUrl: u.avatarUrl || '',
          balance: centsJson(balance),
          inventoryValue: centsJson(inventoryValue),
          totalWealth,
          itemCount: u.inventory.length,
        };
      })
      .sort((a, b) => (a.totalWealth < b.totalWealth ? 1 : a.totalWealth > b.totalWealth ? -1 : 0))
      .slice(0, 50)
      .map((entry, index) => ({
        rank: index + 1,
        ...entry,
        totalWealth: centsJson(entry.totalWealth),
      }));

    res.json({ leaderboard: ranked });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to load leaderboard' });
  }
});

export default router;
