import type { BirthdayConfigDashboard, BirthdayConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureBirthdayConfig>>): BirthdayConfigDashboard {
  return {
    enabled: config.enabled,
    channelId: config.channelId ?? '',
    roleId: config.roleId ?? '',
    message: config.message,
    timezone: config.timezone
  };
}

export async function getBirthdayDashboard(guildId: string): Promise<BirthdayConfigDashboard> {
  const config = await ensureBirthdayConfig(guildId);
  return toDashboard(config);
}

export async function updateBirthdayDashboard(
  guildId: string,
  patch: BirthdayConfigDashboardPatch
): Promise<BirthdayConfigDashboard> {
  await ensureBirthdayConfig(guildId);

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