import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { QueryAuditLogsDto } from './dto/query-audit-logs.dto';

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

  async list(query: QueryAuditLogsDto) {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const skip = (page - 1) * limit;

    const where: any = {};

    if (query.adminUserId) {
      where.adminUserId = query.adminUserId;
    }
    if (query.action) {
      where.action = query.action;
    }
    if (query.startDate || query.endDate) {
      where.createdAt = {};
      if (query.startDate) {
        where.createdAt.gte = new Date(query.startDate);
      }
      if (query.endDate) {
        where.createdAt.lte = new Date(query.endDate + 'T23:59:59.999Z');
      }
    }

    const [items, total] = await Promise.all([
      this.prisma.adminAuditLog.findMany({
        where,
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
        include: {
          adminUser: {
            select: {
              email: true,
              displayName: true,
            },
          },
        },
      }),
      this.prisma.adminAuditLog.count({ where }),
    ]);

    return {
      items: items.map((item) => ({
        id: item.id,
        adminUserId: item.adminUserId,
        adminUserEmail: item.adminUser.email,
        adminUserDisplayName: item.adminUser.displayName,
        action: item.action,
        resourceType: item.resourceType,
        resourceId: item.resourceId,
        beforeJson: item.beforeJson,
        afterJson: item.afterJson,
        ip: item.ip,
        userAgent: item.userAgent,
        createdAt: item.createdAt.toISOString(),
      })),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async getById(id: string) {
    const log = await this.prisma.adminAuditLog.findUnique({
      where: { id },
      include: {
        adminUser: {
          select: {
            email: true,
            displayName: true,
          },
        },
      },
    });
    if (!log) throw new NotFoundException('审计日志不存在');

    return {
      id: log.id,
      adminUserId: log.adminUserId,
      adminUserEmail: log.adminUser.email,
      adminUserDisplayName: log.adminUser.displayName,
      action: log.action,
      resourceType: log.resourceType,
      resourceId: log.resourceId,
      beforeJson: log.beforeJson,
      afterJson: log.afterJson,
      ip: log.ip,
      userAgent: log.userAgent,
      createdAt: log.createdAt.toISOString(),
    };
  }
}
