import type { AuditItem } from '@/types/api'

/** 统一后端 target_* 与前端 resource_* 字段 */
export function normalizeAuditItem(raw: Record<string, unknown>): AuditItem {
  const targetType = String(raw.target_type ?? raw.resource_type ?? '')
  const targetId = raw.target_id ?? raw.resource_id
  return {
    id: Number(raw.id),
    admin_username: String(raw.admin_username ?? ''),
    action: String(raw.action ?? ''),
    resource_type: targetType,
    target_type: targetType,
    resource_id: targetId != null && targetId !== '' ? Number(targetId) : null,
    target_id: targetId != null && targetId !== '' ? Number(targetId) : null,
    detail: raw.detail != null ? String(raw.detail) : null,
    ip_address: raw.ip_address != null ? String(raw.ip_address) : null,
    created_at: raw.created_at != null ? String(raw.created_at) : null,
  }
}

export function normalizeAuditList(items: unknown[]): AuditItem[] {
  return items.map((row) => normalizeAuditItem(row as Record<string, unknown>))
}
