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

export interface AuditLogInput {
  adminUserId: string;
  action: string;
  resourceType?: string;
  resourceId?: string;
  beforeJson?: any;
  afterJson?: any;
  ip?: string;
  userAgent?: string;
  riskLevel?: 'low' | 'medium' | 'high' | 'critical';
  reason?: string;
}

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

  async log(input: AuditLogInput) {
    await this.prisma.adminAuditLog.create({
      data: {
        adminUserId: input.adminUserId,
        action: input.action,
        resourceType: input.resourceType ?? null,
        resourceId: input.resourceId ?? null,
        beforeJson: input.beforeJson ?? null,
        afterJson: input.afterJson ?? null,
        ip: input.ip ?? null,
        userAgent: input.userAgent ?? null,
        riskLevel: input.riskLevel ?? this.defaultRisk(input.action),
        reason: input.reason ?? null,
      },
    });
  }

  private defaultRisk(action: string): string {
    if (/delete|remove|purge|revoke|reset|transfer/i.test(action)) return 'critical';
    if (/update|edit|disable|block|freeze/i.test(action)) return 'high';
    if (/create|add|import|upload/i.test(action)) return 'medium';
    return 'low';
  }
}
