import type { VerificationConfigDashboard, VerificationConfigDashboardPatch } from '@nexumi/shared';
import type { Prisma } from '@prisma/client';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureVerificationConfig>>): VerificationConfigDashboard {
  return {
    enabled: config.enabled,
    channelId: config.channelId ?? '',
    verifiedRoleId: config.verifiedRoleId ?? '',
    unverifiedRoleId: config.unverifiedRoleId ?? '',
    mode: config.mode as VerificationConfigDashboard['mode'],
    minAccountAgeDays: config.minAccountAgeDays,
    failAction: config.failAction as VerificationConfigDashboard['failAction']
  };
}

export async function getVerificationDashboard(guildId: string): Promise<VerificationConfigDashboard> {
  const config = await ensureVerificationConfig(guildId);
  return toDashboard(config);
}

export async function updateVerificationDashboard(
  guildId: string,
  patch: VerificationConfigDashboardPatch
): Promise<VerificationConfigDashboard> {
  await ensureVerificationConfig(guildId);

  const { channelId, verifiedRoleId, unverifiedRoleId, ...rest } = patch;
  const data: Prisma.VerificationConfigUpdateInput = { ...rest };
  if (channelId !== undefined) {
    data.channelId = channelId === '' ? null : channelId;
  }
  if (verifiedRoleId !== undefined) {
    data.verifiedRoleId = verifiedRoleId === '' ? null : verifiedRoleId;
  }
  if (unverifiedRoleId !== undefined) {
    data.unverifiedRoleId = unverifiedRoleId === '' ? null : unverifiedRoleId;
  }

  const updated = await prisma.verificationConfig.update({ where: { guildId }, data });
  return toDashboard(updated);
}
