// app/api/usage/route.ts
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';

const PLAN_LIMITS_MB = {
  free: 20480, // 10 GB
  rookie: 30720, // 30 GB
  pro: 1024 * 1024, // 1 TB
};

export async function GET() {
  const session = await getServerSession(authOptions);

  if (!session?.user?.email) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const user = await prisma.user.findUnique({
    where: { email: session.user.email },
    select: {
      id: true,
      plan: true,
    },
  });

  if (!user) {
    return NextResponse.json({ error: 'User not found' }, { status: 404 });
  }

  const plan = (user.plan || 'free') as keyof typeof PLAN_LIMITS_MB;
  const maxMonthlyMB = PLAN_LIMITS_MB[plan];

  const monthStart = new Date();
  monthStart.setDate(1);
  monthStart.setHours(0, 0, 0, 0);

  const usedBytes = await prisma.file.aggregate({
    _sum: {
      size: true,
    },
    where: {
      transfer: {
        is: {
          userId: user.id,
          createdAt: {
            gte: monthStart,
          },
        },
      },
    },
  });

  const usedMB = Math.ceil(Number(usedBytes._sum.size || 0) / 1024 / 1024);
  const remainingMB = Math.max(maxMonthlyMB - usedMB, 0);
  console.log('Used bytes:', usedBytes);

  return NextResponse.json({
    plan,
    usedMB,
    remainingMB,
    maxMonthlyMB,
  });
}
