import type { EscalationAction, ModerationDashboard, ModerationDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

async function ensureGuild(guildId: string): Promise<void> {
  await prisma.guild.upsert({ where: { id: guildId }, update: {}, create: { id: guildId } });
}

async function ensureGuildSettings(guildId: string) {
  await ensureGuild(guildId);
  return prisma.guildSettings.upsert({
    where: { guildId },
    update: {},
    create: { guildId }
  });
}

export async function getModerationDashboard(guildId: string): Promise<ModerationDashboard> {
  const [settings, rules] = await Promise.all([
    ensureGuildSettings(guildId),
    prisma.escalationRule.findMany({ where: { guildId }, orderBy: { warnCount: 'asc' } })
  ]);

  return {
    moderationEnabled: settings.moderationEnabled,
    escalations: rules.map((rule) => ({
      id: rule.id,
      warnCount: rule.warnCount,
      action: rule.action as EscalationAction,
      durationMs: rule.durationMs,
      reason: rule.reason,
      enabled: rule.enabled
    }))
  };
}

export async function updateModerationDashboard(
  guildId: string,
  patch: ModerationDashboardPatch
): Promise<ModerationDashboard> {
  await ensureGuild(guildId);

  if (patch.moderationEnabled !== undefined) {
    await prisma.guildSettings.upsert({
      where: { guildId },
      update: { moderationEnabled: patch.moderationEnabled },
      create: { guildId, moderationEnabled: patch.moderationEnabled }
    });
  }

  if (patch.escalations !== undefined) {
    await prisma.$transaction([
      prisma.escalationRule.deleteMany({ where: { guildId } }),
      ...patch.escalations.map((rule) =>
        prisma.escalationRule.create({
          data: {
            guildId,
            warnCount: rule.warnCount,
            action: rule.action,
            durationMs: rule.durationMs ?? null,
            reason: rule.reason ?? null,
            enabled: rule.enabled
          }
        })
      )
    ]);
  }

  return getModerationDashboard(guildId);
}
