import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';

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

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

  const email = session.user.email;

  // Transfers sent
  const transfersSent = await prisma.transfer.count({
    where: { senderEmail: email },
  });

  // Total files sent - sum of totalFiles field on transfers
  const totalFilesData = await prisma.transfer.aggregate({
    where: { senderEmail: email },
    _sum: {
      totalFiles: true,
    },
  });
  const totalFilesSent = totalFilesData._sum.totalFiles ?? 0;

  // Downloads - count of fileDownload for files in transfers by this sender
  const downloads = await prisma.fileDownload.count({
    where: {
      file: {
        transfer: {
          senderEmail: email,
        },
      },
    },
  });

  // Active transfers - example: transfers not expired yet
  const activeTransfers = await prisma.transfer.count({
    where: {
      senderEmail: email,
      expiresAt: {
        gt: new Date(),
      },
    },
  });

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

  const transfersThisMonth = await prisma.transfer.count({
    where: {
      senderEmail: email,
      createdAt: {
        gte: startOfMonth,
      },
    },
  });

  const remainingTransfers = Math.max(10 - transfersThisMonth, 0);

  return NextResponse.json({
    transfersSent,
    totalFilesSent,
    downloads,
    activeTransfers,
    remainingTransfers,
  });
}
