import { Injectable } from "@nestjs/common";
import { Prisma } from "@jorgecuadros/database";
import { PrismaService } from "../prisma/prisma.service";

/**
 * Thin writer over the existing ActivityLog model. Every mutating route calls
 * this so who-did-what is recorded — the structural replacement for the old
 * PHP app's scattered Logger calls. Best-effort: a logging failure must never
 * fail the underlying write, so callers `void audit.log(...)` without awaiting.
 */
@Injectable()
export class AuditService {
  constructor(private readonly prisma: PrismaService) {}

  async log(
    userId: string | null | undefined,
    event: string,
    message?: Record<string, unknown>,
    level = "info",
  ): Promise<void> {
    try {
      await this.prisma.activityLog.create({
        data: {
          userId: userId ?? undefined,
          event,
          level,
          message: (message as Prisma.InputJsonValue) ?? undefined,
        },
      });
    } catch {
      /* never let audit logging break a real write */
    }
  }
}
