import {
  WelcomeEmbedSchema,
  type WelcomeConfigDashboard,
  type WelcomeConfigDashboardPatch,
  type WelcomeEmbed
} from '@nexumi/shared';
import { Prisma } from '@prisma/client';
import { prisma } from '../prisma';

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

function parseEmbed(raw: unknown): WelcomeEmbed | null {
  const parsed = WelcomeEmbedSchema.safeParse(raw);
  return parsed.success ? parsed.data : null;
}

function toDashboard(config: Awaited<ReturnType<typeof ensureWelcomeConfig>>): WelcomeConfigDashboard {
  return {
    welcomeEnabled: config.welcomeEnabled,
    leaveEnabled: config.leaveEnabled,
    welcomeChannelId: config.welcomeChannelId ?? '',
    leaveChannelId: config.leaveChannelId ?? '',
    welcomeType: config.welcomeType as WelcomeConfigDashboard['welcomeType'],
    welcomeContent: config.welcomeContent,
    welcomeEmbed: parseEmbed(config.welcomeEmbed),
    leaveContent: config.leaveContent,
    leaveEmbed: parseEmbed(config.leaveEmbed),
    welcomeDmEnabled: config.welcomeDmEnabled,
    welcomeDmContent: config.welcomeDmContent,
    userAutoroleIds: config.userAutoroleIds,
    botAutoroleIds: config.botAutoroleIds,
    imageTitle: config.imageTitle,
    imageSubtitle: config.imageSubtitle
  };
}

export async function getWelcomeDashboard(guildId: string): Promise<WelcomeConfigDashboard> {
  const config = await ensureWelcomeConfig(guildId);
  return toDashboard(config);
}

export async function updateWelcomeDashboard(
  guildId: string,
  patch: WelcomeConfigDashboardPatch
): Promise<WelcomeConfigDashboard> {
  await ensureWelcomeConfig(guildId);

  const { welcomeChannelId, leaveChannelId, welcomeEmbed, leaveEmbed, ...rest } = patch;

  const data: Prisma.WelcomeConfigUpdateInput = { ...rest };
  if (welcomeChannelId !== undefined) {
    data.welcomeChannelId = welcomeChannelId === '' ? null : welcomeChannelId;
  }
  if (leaveChannelId !== undefined) {
    data.leaveChannelId = leaveChannelId === '' ? null : leaveChannelId;
  }
  if (welcomeEmbed !== undefined) {
    data.welcomeEmbed = welcomeEmbed === null ? Prisma.JsonNull : (welcomeEmbed as Prisma.InputJsonValue);
  }
  if (leaveEmbed !== undefined) {
    data.leaveEmbed = leaveEmbed === null ? Prisma.JsonNull : (leaveEmbed as Prisma.InputJsonValue);
  }

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