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

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;

  const transfers = await prisma.transfer.findMany({
    where: {
      senderEmail: email,
    },
    include: {
      files: true,
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  // `size` is a BigInt column and JSON.stringify throws on BigInt, so every
  // value crossing the response boundary is converted to Number here.
  const formattedTransfers = transfers.map((t) => ({
    id: t.id,
    senderEmail: t.senderEmail,
    recipientEmail: t.recipientEmail,
    message: t.message,
    createdAt: t.createdAt.toISOString(),
    expiresAt: t.expiresAt.toISOString(),
    status: t.status,
    totalFiles: t.totalFiles ?? t.files.length,
    totalSize: Number(t.files.reduce((sum, f) => sum + f.size, BigInt(0))),
    downloadCount: 0, // optionally calculate from FileDownload
    downloadUrl: t.downloadUrl,
    files: t.files.map((f) => ({
      id: f.id,
      name: f.name,
      size: Number(f.size),
    })),
  }));

  return NextResponse.json({ transfers: formattedTransfers });
}
