import "server-only";

import { headers } from "next/headers";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

type AuditInput = {
  actorId?: string | null;
  action: string;
  entityType: string;
  entityId?: string | null;
  metadata?: Record<string, unknown>;
};

export async function writeAuditLog(input: AuditInput) {
  try {
    const headerStore = await headers();
    const forwardedFor = headerStore.get("x-forwarded-for");
    const ipAddress = forwardedFor?.split(",")[0]?.trim() ?? null;
    const userAgent = headerStore.get("user-agent");
    const supabase = createAdminSupabaseClient();

    await supabase.from("audit_logs").insert({
      actor_id: input.actorId ?? null,
      action: input.action,
      entity_type: input.entityType,
      entity_id: input.entityId ?? null,
      metadata: input.metadata ?? {},
      ip_address: ipAddress,
      user_agent: userAgent
    });
  } catch {
    // Audit failures must not disclose sensitive context in application logs.
  }
}
