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

export interface RecordAuditParams {
  tenantId: string;
  entityType: string;
  entityId: string;
  action: string;
  summary: string;
  details?: any;
  userId?: string | null;
  customerId?: string | null;
}

@Injectable()
export class AuditService {
  constructor(private readonly prisma: PrismaService) {}

  async record(params: RecordAuditParams) {
    try {
      return await this.prisma.auditEvent.create({
        data: {
          tenantId: params.tenantId,
          entityType: params.entityType,
          entityId: params.entityId,
          action: params.action,
          summary: params.summary,
          details: params.details ?? undefined,
          userId: params.userId ?? null,
          customerId: params.customerId ?? null,
        },
      });
    } catch (err) {
      console.error('Failed to write audit event:', err);
      return null;
    }
  }

  async listForEntity(tenantId: string, entityType: string, entityId: string) {
    return this.prisma.auditEvent.findMany({
      where: { tenantId, entityType, entityId },
      include: { user: { select: { id: true, name: true, email: true } } },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });
  }

  async listForCustomer(tenantId: string, customerId: string) {
    return this.prisma.auditEvent.findMany({
      where: { tenantId, customerId },
      include: { user: { select: { id: true, name: true, email: true } } },
      orderBy: { createdAt: 'desc' },
      take: 100,
    });
  }
}
