"use server"

import { createId } from "@paralleldrive/cuid2"
import { db } from "@/shared/db"
import { auditLogs } from "@/shared/db/schema"
import { getSession } from "@/shared/lib/session"
import { resolveClientIp, getUserAgent } from "@/shared/lib/http-utils"

export type AuditLogStatus = "success" | "failure"

export interface LogAuditParams {
  action: string
  module: string
  targetId?: string
  targetType?: string
  detail?: Record<string, unknown>
  status?: AuditLogStatus
}

/**
 * Record an audit log entry for the current authenticated user.
 * Silently fails on error so it never breaks the main operation.
 */
export async function logAudit(params: LogAuditParams): Promise<void> {
  try {
    const session = await getSession()
    const ipAddress = await resolveClientIp()
    const userAgent = await getUserAgent()

    await db.insert(auditLogs).values({
      id: createId(),
      userId: session?.user?.id ?? "unknown",
      userName: session?.user?.name ?? "unknown",
      action: params.action,
      module: params.module,
      targetId: params.targetId ?? null,
      targetType: params.targetType ?? null,
      detail: params.detail ? JSON.stringify(params.detail) : null,
      ipAddress,
      userAgent,
      status: params.status ?? "success",
    })
  } catch {
    // Silently fail - logging should not break the main operation
  }
}
