import type { AuditTrailRecord } from "@/types/audit-trail";

type SerializableAuditTrail = {
  id: bigint;
  action: string;
  entityType: string;
  entityId: string | null;
  method: string;
  pathname: string;
  statusCode: number;
  summary: string | null;
  occurredAt: Date;
  metadata: unknown;
  user: {
    id: bigint;
    name: string;
    email: string | null;
    username: string | null;
    role: { code: string };
  } | null;
};

export function serializeAuditTrail(item: SerializableAuditTrail): AuditTrailRecord {
  return {
    id: item.id.toString(),
    action: item.action,
    entity_type: item.entityType,
    entity_id: item.entityId,
    method: item.method,
    pathname: item.pathname,
    status_code: item.statusCode,
    summary: item.summary,
    occurred_at: item.occurredAt.toISOString(),
    user: item.user
      ? {
          id: item.user.id.toString(),
          name: item.user.name,
          email: item.user.email,
          username: item.user.username,
          role: item.user.role.code
        }
      : null,
    metadata:
      item.metadata && typeof item.metadata === "object" && !Array.isArray(item.metadata)
        ? (item.metadata as Record<string, unknown>)
        : null
  };
}
