import type { GuildGeneralSettings, GuildGeneralSettingsPatch } from '@nexumi/shared';
import { prisma } from './prisma';

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

  return prisma.guildSettings.upsert({
    where: { guildId },
    update: {},
    create: { guildId }
  });
}

function toGeneralSettings(settings: {
  locale: string;
  timezone: string;
  moderationEnabled: boolean;
  snipeEnabled: boolean;
}): GuildGeneralSettings {
  return {
    locale: settings.locale === 'en' ? 'en' : 'de',
    timezone: settings.timezone,
    moderationEnabled: settings.moderationEnabled,
    snipeEnabled: settings.snipeEnabled
  };
}

export async function getGuildGeneralSettings(guildId: string): Promise<GuildGeneralSettings> {
  const settings = await ensureGuildSettings(guildId);
  return toGeneralSettings(settings);
}

export async function updateGuildGeneralSettings(
  guildId: string,
  patch: GuildGeneralSettingsPatch
): Promise<GuildGeneralSettings> {
  await ensureGuildSettings(guildId);
  const updated = await prisma.guildSettings.update({
    where: { guildId },
    data: patch
  });
  return toGeneralSettings(updated);
}
