import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

export interface AuditEventInput {
  actorId?: string | null;
  action: string;
  resourceType: string;
  resourceId: string;
  productId?: string | null;
  projectId?: string | null;
  versionId?: string | null;
  before?: unknown;
  after?: unknown;
  metadata?: unknown;
}

@Injectable()
export class AuditService {
  private readonly logger = new Logger(AuditService.name);

  constructor(private readonly prisma: PrismaService) {}

  async record(input: AuditEventInput): Promise<void> {
    try {
      await this.prisma.auditLog.create({
        data: {
          actorId: input.actorId ?? null,
          action: input.action,
          resourceType: input.resourceType,
          resourceId: input.resourceId,
          productId: input.productId ?? null,
          projectId: input.projectId ?? null,
          versionId: input.versionId ?? null,
          before: input.before ?? {},
          after: input.after ?? {},
          metadata: input.metadata ?? {},
        },
      });
    } catch (error: any) {
      this.logger.warn(`Audit write failed for ${input.action}: ${error?.message ?? error}`);
    }
  }
}
