import { BOT_STATUS_REDIS_KEY, BotStatusPayloadSchema, PRESENCE_REDIS_KEY } from '@nexumi/shared';
import { prisma } from './prisma';
import { redis } from './redis';

export async function getPublicStatus() {
  const [rawStatus, rawPresence, updates] = await Promise.all([
    redis.get(BOT_STATUS_REDIS_KEY),
    redis.get(PRESENCE_REDIS_KEY),
    prisma.changelogEntry.findMany({
      orderBy: { publishedAt: 'desc' },
      take: 10
    })
  ]);

  let botStatus = null;
  if (rawStatus) {
    const parsed = BotStatusPayloadSchema.safeParse(JSON.parse(rawStatus));
    botStatus = parsed.success ? parsed.data : null;
  }

  let maintenanceMode = false;
  if (rawPresence) {
    try {
      const presence = JSON.parse(rawPresence) as { maintenanceMode?: boolean };
      maintenanceMode = Boolean(presence.maintenanceMode);
    } catch {
      maintenanceMode = false;
    }
  } else {
    const row = await prisma.botPresenceConfig.findUnique({ where: { id: 'singleton' } });
    maintenanceMode = row?.maintenanceMode ?? false;
  }

  const degraded = !botStatus;
  const overall = maintenanceMode ? 'maintenance' : degraded ? 'degraded' : 'operational';

  return {
    ok: !maintenanceMode,
    overall,
    maintenanceMode,
    degraded,
    shards: botStatus?.shards ?? [],
    apiLatencyMs: botStatus?.apiLatencyMs ?? null,
    guildCount: botStatus?.guildCount ?? (await prisma.guild.count()),
    uptimeSeconds: botStatus?.uptimeSeconds ?? null,
    updates: updates.map((entry) => ({
      id: entry.id,
      version: entry.version,
      title: entry.title,
      body: entry.body,
      publishedAt: entry.publishedAt.toISOString(),
      isIncident: entry.version.toLowerCase().startsWith('incident')
    })),
    updatedAt: botStatus?.updatedAt ?? new Date().toISOString()
  };
}
