import { AuditAction, Prisma } from '@prisma/client';
import { prisma } from '../../lib/prisma';

interface AuditFilters {
  action?: AuditAction;
  instanceId?: string;
  userId?: string;
  from?: string;
  to?: string;
}

export async function listAuditLogs(
  filters: AuditFilters,
  page = 1,
  limit = 50
) {
  const where: Prisma.AuditLogWhereInput = {};

  if (filters.action) where.action = filters.action;
  if (filters.instanceId) where.instanceId = filters.instanceId;
  if (filters.userId) where.userId = filters.userId;
  if (filters.from || filters.to) {
    where.createdAt = {};
    if (filters.from) where.createdAt.gte = new Date(filters.from);
    if (filters.to) where.createdAt.lte = new Date(filters.to);
  }

  const [data, total] = await Promise.all([
    prisma.auditLog.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * limit,
      take: limit,
      include: {
        user: { select: { id: true, email: true, name: true } },
        instance: { select: { id: true, name: true, slug: true } },
      },
    }),
    prisma.auditLog.count({ where }),
  ]);

  return { data, total, page, limit };
}
