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 divisions = db.prepare('SELECT * FROM recruitment_config WHERE guild_id = ? ORDER BY id ASC').all(guildId);
  const stats = {
    total: (db.prepare('SELECT COUNT(*) as c FROM recruitment_entries WHERE guild_id = ?').get(guildId) as any).c,
    pending: (db.prepare('SELECT COUNT(*) as c FROM recruitment_entries WHERE guild_id = ? AND status = ?').get(guildId, 'pending') as any).c,
    approved: (db.prepare('SELECT COUNT(*) as c FROM recruitment_entries WHERE guild_id = ? AND status = ?').get(guildId, 'approved') as any).c,
  };
  const entries = db.prepare('SELECT * FROM recruitment_entries WHERE guild_id = ? ORDER BY created_at DESC LIMIT 50').all(guildId);

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

export async function POST(req: 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 { division_name, prefix, role_id, button_label, button_emoji, button_style } = await req.json();

  const db = getDb();
  db.prepare(
    'INSERT OR REPLACE INTO recruitment_config (guild_id, division_name, prefix, role_id, button_label, button_emoji, button_style) VALUES (?, ?, ?, ?, ?, ?, ?)'
  ).run(guildId, division_name, prefix, role_id || null, button_label || division_name, button_emoji || '🛡️', button_style || 'Primary');
  db.close();

  return NextResponse.json({ success: true });
}

export async function DELETE(req: 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 { id } = await req.json();

  const db = getDb();
  db.prepare('DELETE FROM recruitment_config WHERE id = ? AND guild_id = ?').run(id, guildId);
  db.close();

  return NextResponse.json({ success: true });
}
