import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { NextResponse } from 'next/server';
import Database from 'better-sqlite3';
import path from 'path';

function getDb() {
  return new Database(path.join(process.cwd(), '..', 'data', 'bot.db'));
}

export async function GET(_: Request, { params }: { params: Promise<{ guildId: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { guildId } = await params;
  const db = getDb();

  const stats = {
    total: (db.prepare('SELECT COUNT(*) as c FROM leaves WHERE guild_id = ?').get(guildId) as any).c,
    pending: (db.prepare("SELECT COUNT(*) as c FROM leaves WHERE guild_id = ? AND status = 'pending'").get(guildId) as any).c,
    active: (db.prepare("SELECT COUNT(*) as c FROM leaves WHERE guild_id = ? AND status = 'approved'").get(guildId) as any).c,
  };

  const entries = db.prepare('SELECT * FROM leaves WHERE guild_id = ? ORDER BY created_at DESC LIMIT 50').all(guildId);

  db.close();
  return NextResponse.json({ stats, entries });
}
