import type { CaseDashboard, CaseListQuery, CaseUpdateDashboard } 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
  }));
}

export async function updateCaseReason(
  guildId: string,
  caseId: string,
  patch: CaseUpdateDashboard
): Promise<CaseDashboard | null> {
  const existing = await prisma.case.findFirst({
    where: { id: caseId, guildId, deletedAt: null }
  });
  if (!existing) {
    return null;
  }
  const updated = await prisma.case.update({
    where: { id: existing.id },
    data: { reason: patch.reason }
  });
  return {
    id: updated.id,
    caseNumber: updated.caseNumber,
    targetUserId: updated.targetUserId,
    moderatorId: updated.moderatorId,
    action: updated.action,
    reason: updated.reason,
    createdAt: updated.createdAt.toISOString(),
    deletedAt: updated.deletedAt ? updated.deletedAt.toISOString() : null
  };
}

export async function softDeleteCase(guildId: string, caseId: string): Promise<boolean> {
  const existing = await prisma.case.findFirst({
    where: { id: caseId, guildId, deletedAt: null }
  });
  if (!existing) {
    return false;
  }
  await prisma.case.update({
    where: { id: existing.id },
    data: { deletedAt: new Date() }
  });
  return true;
}
