import type { CommandGlobalRules, CommandGlobalRulesPatch } 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 toRules(settings: {
  commandAllowedChannelIds: string[];
  commandDeniedChannelIds: string[];
}): CommandGlobalRules {
  return {
    allowedChannelIds: settings.commandAllowedChannelIds,
    deniedChannelIds: settings.commandDeniedChannelIds
  };
}

export async function getCommandGlobalRules(guildId: string): Promise<CommandGlobalRules> {
  const settings = await ensureGuildSettings(guildId);
  return toRules(settings);
}

export async function updateCommandGlobalRules(
  guildId: string,
  patch: CommandGlobalRulesPatch
): Promise<CommandGlobalRules> {
  await ensureGuildSettings(guildId);
  const updated = await prisma.guildSettings.update({
    where: { guildId },
    data: {
      ...(patch.allowedChannelIds !== undefined
        ? { commandAllowedChannelIds: patch.allowedChannelIds }
        : {}),
      ...(patch.deniedChannelIds !== undefined
        ? { commandDeniedChannelIds: patch.deniedChannelIds }
        : {})
    }
  });
  return toRules(updated);
}
