import { createAdminClient } from "@/lib/supabase/admin";
import { AuthenticatedUser } from "@/types/auth";

export interface LogAuditParams {
  actor?: AuthenticatedUser | null;
  action: string;
  entityType: string;
  entityId: string;
  oldState?: Record<string, unknown> | null;
  newState?: Record<string, unknown> | null;
  ipAddress?: string | null;
  userAgent?: string | null;
}

/**
 * Record an immutable audit log entry for governance and compliance
 */
export async function logAuditEvent({
  actor,
  action,
  entityType,
  entityId,
  oldState = null,
  newState = null,
  ipAddress = null,
  userAgent = null,
}: LogAuditParams): Promise<void> {
  try {
    const supabase = createAdminClient();

    await supabase.from("audit_logs").insert({
      actor_user_id: actor?.id || null,
      actor_role: actor?.roles?.[0] || null,
      action,
      entity_type: entityType,
      entity_id: entityId,
      old_state: oldState,
      new_state: newState,
      ip_address: ipAddress,
      user_agent: userAgent,
    });
  } catch (err) {
    console.error("[Audit Log Error] Failed to write audit event:", err);
  }
}
