import { createAdminAuditLog, listAdminAuditLogs } from '../../repositories/admin-audit-log-repo.js'
import { nowIso } from '../../utils/time.js'
import {
  normalizeDateQuery,
  normalizePage,
  normalizePageSize,
  safeParseJson,
} from './admin-query-utils.js'
import type { JsonObject } from '../../types/json.js'

export async function writeAdminAuditLog(
  session: JsonObject | null | undefined,
  payload: JsonObject = {},
) {
  if (!session?.userId) {
    return null
  }

  return createAdminAuditLog({
    actorUserId: session.userId,
    actorUsername: session.username,
    actorRole: session.role,
    action: String(payload.action || '').trim(),
    targetType: String(payload.targetType || '').trim() || 'unknown',
    targetId: String(payload.targetId || '').trim(),
    payloadJson: JSON.stringify(payload.data || {}),
    createdAt: nowIso(),
  })
}

export async function getAdminAuditLogs(query: JsonObject = {}) {
  const page = normalizePage(query.page)
  const pageSize = normalizePageSize(query.pageSize)
  const { items, total } = await listAdminAuditLogs({
    page,
    pageSize,
    actorUsername: String(query.actorUsername || '').trim(),
    action: String(query.action || '').trim(),
    targetType: String(query.targetType || '').trim(),
    dateFrom: normalizeDateQuery(query.dateFrom),
    dateTo: normalizeDateQuery(query.dateTo, true),
  })

  return {
    items: items.map((item) => ({
      logId: Number(item.id),
      actorUserId: Number(item.actor_user_id || 0),
      actorUsername: item.actor_username,
      actorRole: item.actor_role,
      action: item.action,
      targetType: item.target_type,
      targetId: item.target_id,
      payload: safeParseJson(item.payload_json),
      createdAt: item.created_at,
    })),
    pagination: { page, pageSize, total },
  }
}
