import type { TempVoiceConfigDashboard, TempVoiceConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureTempVoiceConfig>>): TempVoiceConfigDashboard {
  return {
    enabled: config.enabled,
    hubChannelId: config.hubChannelId ?? '',
    categoryId: config.categoryId ?? '',
    defaultName: config.defaultName,
    defaultLimit: config.defaultLimit
  };
}

export async function getTempVoiceDashboard(guildId: string): Promise<TempVoiceConfigDashboard> {
  const config = await ensureTempVoiceConfig(guildId);
  return toDashboard(config);
}

export async function updateTempVoiceDashboard(
  guildId: string,
  patch: TempVoiceConfigDashboardPatch
): Promise<TempVoiceConfigDashboard> {
  await ensureTempVoiceConfig(guildId);

  const { hubChannelId, categoryId, ...rest } = patch;
  const updated = await prisma.tempVoiceConfig.update({
    where: { guildId },
    data: {
      ...rest,
      ...(hubChannelId !== undefined ? { hubChannelId: hubChannelId === '' ? null : hubChannelId } : {}),
      ...(categoryId !== undefined ? { categoryId: categoryId === '' ? null : categoryId } : {})
    }
  });
  return toDashboard(updated);
}
