import type { FunConfigDashboard, FunConfigDashboardPatch } from '@nexumi/shared';
import { redis } from '../redis';

function funConfigKey(guildId: string): string {
  return `fun:config:${guildId}`;
}

export async function getFunDashboard(guildId: string): Promise<FunConfigDashboard> {
  const raw = await redis.get(funConfigKey(guildId));
  if (!raw) {
    return { enabled: true, mediaEnabled: true };
  }
  try {
    const parsed = JSON.parse(raw) as Partial<FunConfigDashboard>;
    return { enabled: parsed.enabled ?? true, mediaEnabled: parsed.mediaEnabled ?? true };
  } catch {
    return { enabled: true, mediaEnabled: true };
  }
}

export async function updateFunDashboard(
  guildId: string,
  patch: FunConfigDashboardPatch
): Promise<FunConfigDashboard> {
  const current = await getFunDashboard(guildId);
  const next: FunConfigDashboard = { ...current, ...patch };
  await redis.set(funConfigKey(guildId), JSON.stringify(next));
  return next;
}
