import type { Knex } from 'knex';
import { db } from '../../db/knex';

export type AuditInput = {
  adminId: string | null;
  action: string;
  entity: string;
  entityId?: string | number | null;
  label?: string;
  diff?: unknown;
};

/** Every admin create/update/delete writes audit_log (BACKEND.md §5). Pass the transaction when inside one. */
export async function audit(input: AuditInput, trx: Knex | Knex.Transaction = db) {
  await trx('audit_log').insert({
    admin_id: input.adminId,
    action: input.action,
    entity: input.entity,
    entity_id: input.entityId == null ? null : String(input.entityId),
    label: input.label?.slice(0, 190) ?? null,
    diff: input.diff === undefined ? null : JSON.stringify(input.diff),
  });
}

/** Shallow diff of changed fields for the audit log (long text is truncated). */
export function diffOf(before: Record<string, unknown> | undefined, after: Record<string, unknown>) {
  const out: Record<string, { from: unknown; to: unknown }> = {};
  const short = (v: unknown) => (typeof v === 'string' && v.length > 200 ? `${v.slice(0, 200)}…` : v);
  for (const [k, v] of Object.entries(after)) {
    const prev = before?.[k];
    if (JSON.stringify(prev) !== JSON.stringify(v)) out[k] = { from: short(prev), to: short(v) };
  }
  return out;
}
