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

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

  async log(data: {
    operatorId?: bigint;
    operatorType: string;
    action: string;
    module: string;
    targetType?: string;
    targetId?: string;
    beforeData?: unknown;
    afterData?: unknown;
    ipAddress?: string;
  }) {
    return this.prisma.auditLog.create({
      data: {
        operatorId: data.operatorId,
        operatorType: data.operatorType,
        action: data.action,
        module: data.module,
        targetType: data.targetType,
        targetId: data.targetId,
        beforeData: data.beforeData ? JSON.stringify(data.beforeData) : null,
        afterData: data.afterData ? JSON.stringify(data.afterData) : null,
        ipAddress: data.ipAddress,
      },
    });
  }

  async list(page = 1, pageSize = 10, module?: string) {
    const skip = (page - 1) * pageSize;
    const where = module ? { module } : {};
    const [items, total] = await Promise.all([
      this.prisma.auditLog.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: pageSize,
      }),
      this.prisma.auditLog.count({ where }),
    ]);
    return { items, total, page, pageSize };
  }
}
