import type { StatsConfigDashboard, StatsConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureStatsConfig>>): StatsConfigDashboard {
  return {
    enabled: config.enabled,
    membersChannelId: config.membersChannelId ?? '',
    onlineChannelId: config.onlineChannelId ?? '',
    boostsChannelId: config.boostsChannelId ?? '',
    membersTemplate: config.membersTemplate,
    onlineTemplate: config.onlineTemplate,
    boostsTemplate: config.boostsTemplate
  };
}

export async function getStatsDashboard(guildId: string): Promise<StatsConfigDashboard> {
  const config = await ensureStatsConfig(guildId);
  return toDashboard(config);
}

export async function updateStatsDashboard(
  guildId: string,
  patch: StatsConfigDashboardPatch
): Promise<StatsConfigDashboard> {
  await ensureStatsConfig(guildId);

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