import type { CaseDashboard, CaseListQuery } from '@nexumi/shared';
import type { Prisma } from '@prisma/client';
import { prisma } from '../prisma';

export async function listCases(guildId: string, query: CaseListQuery): Promise<CaseDashboard[]> {
  const where: Prisma.CaseWhereInput = {
    guildId,
    deletedAt: null
  };

  if (query.action) {
    where.action = query.action;
  }

  if (query.search) {
    where.OR = [
      { targetUserId: { contains: query.search } },
      { moderatorId: { contains: query.search } },
      { reason: { contains: query.search, mode: 'insensitive' } }
    ];
  }

  const cases = await prisma.case.findMany({
    where,
    orderBy: { createdAt: 'desc' },
    take: query.limit
  });

  return cases.map((entry) => ({
    id: entry.id,
    caseNumber: entry.caseNumber,
    targetUserId: entry.targetUserId,
    moderatorId: entry.moderatorId,
    action: entry.action,
    reason: entry.reason,
    createdAt: entry.createdAt.toISOString(),
    deletedAt: entry.deletedAt ? entry.deletedAt.toISOString() : null
  }));
}
