import { prisma } from '@/lib/prisma'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth-options'

interface AuditLogInput {
  action: 'CREATE' | 'UPDATE' | 'DELETE' | 'LOGIN' | 'LOGOUT' | 'STATUS_CHANGE'
  module: string
  entity: string
  entityId?: string
  description: string
  oldValues?: Record<string, unknown>
  newValues?: Record<string, unknown>
  req?: Request
}

export async function logAudit(input: AuditLogInput): Promise<void> {
  try {
    let userId: string | null = null

    try {
      const session = await getServerSession(authOptions)
      userId = (session?.user as any)?.id || null
    } catch {
      // No session available
    }

    const ipAddress = input.req
      ? input.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
        input.req.headers.get('x-real-ip') || null
      : null

    const userAgent = input.req
      ? input.req.headers.get('user-agent')?.substring(0, 500) || null
      : null

    await prisma.auditLog.create({
      data: {
        userId,
        action: input.action,
        module: input.module,
        entity: input.entity,
        entityId: input.entityId || null,
        description: input.description,
        oldValues: input.oldValues ? JSON.stringify(input.oldValues) : null,
        newValues: input.newValues ? JSON.stringify(input.newValues) : null,
        ipAddress,
        userAgent,
      },
    })
  } catch (error) {
    console.error('[Audit Log Error]:', error instanceof Error ? error.message : 'Unknown')
  }
}
