import type { EconomyConfigDashboard, EconomyConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';

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

function toDashboard(config: Awaited<ReturnType<typeof ensureEconomyConfig>>): EconomyConfigDashboard {
  return {
    enabled: config.enabled,
    currencyName: config.currencyName,
    currencySymbol: config.currencySymbol,
    dailyAmount: config.dailyAmount,
    weeklyAmount: config.weeklyAmount,
    workMin: config.workMin,
    workMax: config.workMax,
    workCooldownSeconds: config.workCooldownSeconds,
    startingBalance: config.startingBalance
  };
}

export async function getEconomyDashboard(guildId: string): Promise<EconomyConfigDashboard> {
  const config = await ensureEconomyConfig(guildId);
  return toDashboard(config);
}

export async function updateEconomyDashboard(
  guildId: string,
  patch: EconomyConfigDashboardPatch
): Promise<EconomyConfigDashboard> {
  await ensureEconomyConfig(guildId);
  const updated = await prisma.economyConfig.update({ where: { guildId }, data: patch });
  return toDashboard(updated);
}
