"use server"

import { createId } from "@paralleldrive/cuid2"

import { db } from "@/shared/db"
import { dataChangeLogs } from "@/shared/db/schema"
import { getSession } from "@/shared/lib/session"
import { resolveClientIp } from "@/shared/lib/http-utils"

export type DataChangeAction = "create" | "update" | "delete"

export interface LogDataChangeParams {
  tableName: string
  recordId: string
  action: DataChangeAction
  oldValue?: Record<string, unknown>
  newValue?: Record<string, unknown>
}

/**
 * Record a data change log entry for the current authenticated user.
 * Silently fails on error so it never blocks the main operation.
 */
export async function logDataChange(params: LogDataChangeParams): Promise<void> {
  try {
    const session = await getSession()
    const ipAddress = await resolveClientIp()

    await db.insert(dataChangeLogs).values({
      id: createId(),
      tableName: params.tableName,
      recordId: params.recordId,
      action: params.action,
      oldValue: params.oldValue ? JSON.stringify(params.oldValue) : null,
      newValue: params.newValue ? JSON.stringify(params.newValue) : null,
      changedBy: session?.user?.id ?? "unknown",
      changedByName: session?.user?.name ?? "unknown",
      ipAddress,
    })
  } catch {
    // Silently fail - change logging must not break the main operation
  }
}
