import { prisma } from './prisma'
import { config } from '../../config/app.config'

export async function createToken(downloadId: string): Promise<string> {
  const expiresAt = new Date(
    Date.now() + config.DOWNLOAD_LINK_TTL_HOURS * 60 * 60 * 1000
  )
  const record = await prisma.downloadToken.create({
    data: { downloadId, expiresAt },
  })
  return record.token
}

export async function validateToken(
  token: string
): Promise<{ downloadId: string; filePath: string } | null> {
  const record = await prisma.downloadToken.findUnique({
    where: { token },
    include: { download: { select: { id: true, filePath: true } } },
  })
  if (!record) return null
  if (record.expiresAt < new Date()) return null
  if (!record.download.filePath) return null
  return { downloadId: record.download.id, filePath: record.download.filePath }
}
