/**
 * Audit log queue consumer — tenant-audit-log spec.
 *
 * Drains the `audit-log-queue` Cloudflare Queue.
 * For each message, inserts one row into `tenant_audit_log` via Drizzle.
 *
 * Retry semantics: if an insert fails, the error propagates out of the batch
 * handler, which triggers Cloudflare Queue retry (max_retries = 3, exponential
 * backoff). After 3 failures the message is dropped (acceptable trade-off per spec).
 *
 * Consumer is insert-only: no UPDATEs or DELETEs.
 */
// No insertAuditEvent query helper exists yet; uses raw schema import per audit-log design doc
import { createDb, tenantAuditLog } from '@zync/db'
import { getTenantById } from '@zync/db/queries'
import type { AuditEvent, TenantId } from '@zync/types'
import type { Env } from '@zync/types'

export async function handleAuditLogBatch(
  batch: MessageBatch<AuditEvent>,
  env: Env,
): Promise<void> {
  const db = createDb(env)

  for (const msg of batch.messages) {
    const e = msg.body

    if (!e.tenantId) {
      msg.ack()
      continue
    }

    const tenant = await getTenantById(db, e.tenantId as TenantId)
    if (!tenant) {
      msg.ack()
      continue
    }

    await db.insert(tenantAuditLog).values({
      tenantId: e.tenantId,
      userId: e.userId ?? null,
      actorName: e.actorName ?? null,
      actorEmail: e.actorEmail ?? null,
      eventType: e.eventType,
      entityType: e.entityType ?? null,
      entityId: e.entityId ?? null,
      entityLabel: e.entityLabel ?? null,
      // metadata stored as JSONB object directly — no JSON.stringify
      metadata: e.metadata ?? null,
      ipAddress: e.ipAddress ?? null,
    })

    msg.ack()
  }
}
