import { Injectable } from '@nestjs/common';
import { DbService, Tx } from '@/common/db/db.service';
import { auditLogs } from '@/db/schema';
import { getRequestContext } from '@/common/context/request-context';

export interface AuditEntry {
  action: string; // e.g. "asn.close"
  entityType?: string;
  entityId?: string;
  before?: unknown;
  after?: unknown;
  tenantId?: string | null;
}

/**
 * Writes audit rows in the caller's transaction so audit and business change
 * commit (or roll back) together.
 */
@Injectable()
export class AuditService {
  constructor(private readonly db: DbService) {}

  async log(entry: AuditEntry, tx: Tx): Promise<void> {
    const ctx = getRequestContext();
    await tx.insert(auditLogs).values({
      tenantId: entry.tenantId !== undefined ? entry.tenantId : (ctx?.tenantId ?? null),
      actorType: ctx?.actorType ?? 'SYSTEM',
      actorId: ctx?.actorId ?? 'system',
      actorName: ctx?.actorName ?? 'system',
      action: entry.action,
      entityType: entry.entityType,
      entityId: entry.entityId,
      before: entry.before ?? null,
      after: entry.after ?? null,
      ip: ctx?.ip,
      userAgent: ctx?.userAgent,
      requestId: ctx?.requestId,
    });
  }
}
