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

// Resolves the transfer only if the signed-in user owns it. Returns null for
// both "missing" and "not yours" so the response can't be used to enumerate IDs.
async function findOwnedTransfer(id: string) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.email) return { transfer: null, unauthenticated: true };

  const transferId = Number(id);
  if (!Number.isInteger(transferId)) return { transfer: null, unauthenticated: false };

  const transfer = await prisma.transfer.findFirst({
    where: { id: transferId, senderEmail: session.user.email },
    include: { files: { include: { downloads: true } } },
  });

  return { transfer, unauthenticated: false };
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { transfer, unauthenticated } = await findOwnedTransfer(id);

    if (unauthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    if (!transfer) {
      return NextResponse.json({ error: 'Transfer not found' }, { status: 404 });
    }

    // Soft delete: mark status as DELETED
    await prisma.transfer.update({
      where: { id: transfer.id },
      data: { status: 'DELETED' },
    });

    return NextResponse.json({ success: true, id: transfer.id });
  } catch (error) {
    console.error('Error deleting transfer:', error);
    return NextResponse.json({ error: 'Failed to delete transfer' }, { status: 500 });
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { transfer, unauthenticated } = await findOwnedTransfer(id);

    if (unauthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    if (!transfer) {
      return NextResponse.json({ error: 'Transfer not found' }, { status: 404 });
    }

    // file.size is a BigInt column; seed the accumulator as BigInt and convert
    // once at the end, since JSON.stringify cannot serialize BigInt.
    const totalSize = transfer.files.reduce((sum, file) => sum + file.size, BigInt(0));
    const totalDownloads = transfer.files.reduce((sum, file) => sum + file.downloads.length, 0);

    return NextResponse.json({
      transfer: {
        id: transfer.id,
        senderEmail: transfer.senderEmail,
        recipientEmail: transfer.recipientEmail,
        message: transfer.message,
        filenames: transfer.filenames ? JSON.parse(transfer.filenames) : [],
        createdAt: transfer.createdAt.toISOString(),
        expiresAt: transfer.expiresAt.toISOString(),
        status: transfer.status,
        totalFiles: transfer.totalFiles,
        totalSize: Number(totalSize),
        totalDownloads,
        files: transfer.files.map((file) => ({
          id: file.id,
          name: file.name,
          size: Number(file.size),
          downloadCount: file.downloads.length,
        })),
      },
    });
  } catch (error) {
    console.error('Error fetching transfer:', error);
    return NextResponse.json({ error: 'Failed to fetch transfer' }, { status: 500 });
  }
}
