import { requireAuth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

// GET /api/gamification/xp — get user XP, level, and recent transactions
export async function GET(request: Request) {
  const jwt = await requireAuth(request);
  if (!jwt) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const userId = jwt.userId;

  // Get or create user level
  let userLevel = await prisma.userLevel.findUnique({
    where: { userId },
  });

  if (!userLevel) {
    userLevel = await prisma.userLevel.create({
      data: { userId },
    });
  }

  // Get recent transactions
  const recentTransactions = await prisma.xpTransaction.findMany({
    where: { userId },
    orderBy: { createdAt: "desc" },
    take: 20,
  });

  return NextResponse.json({
    level: userLevel.level,
    xp: userLevel.xp,
    xpToNext: userLevel.xpToNext,
    totalXp: userLevel.xp + (userLevel.level - 1) * calculateXpForLevel(userLevel.level),
    recentTransactions: recentTransactions.map((tx) => ({
      id: tx.id,
      amount: tx.amount,
      reason: tx.reason,
      createdAt: tx.createdAt,
    })),
  });
}

function calculateXpForLevel(level: number): number {
  // Base XP per level: 100 * 1.5^(level-1) cumulative
  let total = 0;
  let xpToNext = 100;
  for (let i = 1; i < level; i++) {
    total += xpToNext;
    xpToNext = Math.floor(xpToNext * 1.5);
  }
  return total;
}
