// src/lib/prisma.ts
import { PrismaClient } from '@prisma/client';
import { TransferStatus } from '@prisma/client';

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma = globalForPrisma.prisma ?? new PrismaClient(); // Changed to a named export

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

export const getTransfer = async (id: string) => {
  const transfer = await prisma.transfer.findUnique({
    where: { id: Number(id) },
    include: {
      files: true,
    },
  });

  if (!transfer) return null;

  // Check if expired and update status
  if (new Date() > transfer.expiresAt && transfer.status === TransferStatus.ACTIVE) {
    await prisma.transfer.update({
      where: { id: Number(id) },
      data: { status: TransferStatus.EXPIRED },
    });
    transfer.status = TransferStatus.EXPIRED;
  }

  return transfer;
};

export const deleteTransfer = async (id: string) => {
  return await prisma.transfer.update({
    where: { id: Number(id) },
    data: { status: TransferStatus.DELETED },
  });
};
