import type { StarboardConfigDashboard, StarboardConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureStarboardConfig>>): StarboardConfigDashboard {
  return {
    enabled: config.enabled,
    channelId: config.channelId ?? '',
    emoji: config.emoji,
    threshold: config.threshold,
    allowSelfStar: config.allowSelfStar,
    ignoredChannelIds: config.ignoredChannelIds
  };
}

export async function getStarboardDashboard(guildId: string): Promise<StarboardConfigDashboard> {
  const config = await ensureStarboardConfig(guildId);
  return toDashboard(config);
}

export async function updateStarboardDashboard(
  guildId: string,
  patch: StarboardConfigDashboardPatch
): Promise<StarboardConfigDashboard> {
  await ensureStarboardConfig(guildId);

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