import crypto from 'crypto'
import type { PrismaClient } from '@prisma/client'

const DEFAULT_INVITE_EXPIRY_HOURS = 72 // 3 days

export function generateInviteToken(): string {
  return crypto.randomBytes(32).toString('hex')
}

export async function getInviteExpiryHours(prisma: PrismaClient): Promise<number> {
  try {
    const setting = await prisma.systemSettings.findUnique({
      where: { key: 'invite_link_expiry_hours' },
      select: { value: true },
    })
    const hours = setting?.value ? parseInt(setting.value, 10) : DEFAULT_INVITE_EXPIRY_HOURS
    return isNaN(hours) || hours < 1 ? DEFAULT_INVITE_EXPIRY_HOURS : hours
  } catch {
    return DEFAULT_INVITE_EXPIRY_HOURS
  }
}

export async function getInviteExpiryMs(prisma: PrismaClient): Promise<number> {
  return (await getInviteExpiryHours(prisma)) * 60 * 60 * 1000
}
