import type { AutomodConfigDashboard, AutomodConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

async function ensureAutoModConfig(guildId: string) {
  await prisma.guild.upsert({ where: { id: guildId }, update: {}, create: { id: guildId } });
  return prisma.autoModConfig.upsert({
    where: { guildId },
    update: {},
    create: { guildId }
  });
}

function toDashboard(config: Awaited<ReturnType<typeof ensureAutoModConfig>>): AutomodConfigDashboard {
  return {
    enabled: config.enabled,
    antiRaidEnabled: config.antiRaidEnabled,
    antiRaidJoinThreshold: config.antiRaidJoinThreshold,
    antiRaidWindowSeconds: config.antiRaidWindowSeconds,
    antiRaidAction: 'LOCKDOWN',
    antiNukeEnabled: config.antiNukeEnabled,
    antiNukeBanThreshold: config.antiNukeBanThreshold,
    antiNukeChannelThreshold: config.antiNukeChannelThreshold,
    antiNukeWindowSeconds: config.antiNukeWindowSeconds,
    lockdownActive: config.lockdownActive
  };
}

export async function getAutomodDashboard(guildId: string): Promise<AutomodConfigDashboard> {
  const config = await ensureAutoModConfig(guildId);
  return toDashboard(config);
}

export async function updateAutomodDashboard(
  guildId: string,
  patch: AutomodConfigDashboardPatch
): Promise<AutomodConfigDashboard> {
  await ensureAutoModConfig(guildId);
  const updated = await prisma.autoModConfig.update({
    where: { guildId },
    data: patch
  });
  return toDashboard(updated);
}
