import { NextResponse } from 'next/server';
import { toApiErrorResponse } from '@/lib/auth';
import { listOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { prisma } from '@/lib/prisma';
import { getPresenceConfig } from '@/lib/owner-presence';

export async function GET() {
  try {
    await requireOwner('VIEWER');
    const [guildCount, blacklistUsers, blacklistGuilds, presence, audit, changelog] =
      await Promise.all([
        prisma.guild.count(),
        prisma.globalUserBlacklist.count(),
        prisma.guildBlacklist.count(),
        getPresenceConfig(),
        listOwnerAudit(10),
        prisma.changelogEntry.findMany({ orderBy: { publishedAt: 'desc' }, take: 5 })
      ]);

    return NextResponse.json({
      guildCount,
      blacklistUsers,
      blacklistGuilds,
      uptimeSeconds: Math.floor(process.uptime()),
      maintenanceMode: presence.maintenanceMode,
      recentAudit: audit,
      changelog: changelog.map((entry) => ({
        id: entry.id,
        version: entry.version,
        title: entry.title,
        publishedAt: entry.publishedAt.toISOString()
      }))
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
