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 types = db.prepare('SELECT * FROM course_types WHERE guild_id = ? ORDER BY name ASC').all(guildId);
  const stats = {
    total: (db.prepare('SELECT COUNT(*) as c FROM courses WHERE guild_id = ?').get(guildId) as any).c,
    scheduled: (db.prepare("SELECT COUNT(*) as c FROM courses WHERE guild_id = ? AND status = 'scheduled'").get(guildId) as any).c,
    completed: (db.prepare("SELECT COUNT(*) as c FROM courses WHERE guild_id = ? AND status = 'completed'").get(guildId) as any).c,
  };
  const recent = db.prepare('SELECT * FROM courses WHERE guild_id = ? ORDER BY created_at DESC LIMIT 20').all(guildId);

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

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 { name, role_id } = await req.json();

  const db = getDb();
  db.prepare('INSERT OR REPLACE INTO course_types (guild_id, name, role_id) VALUES (?, ?, ?)').run(guildId, name, role_id || null);
  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 course_types WHERE id = ? AND guild_id = ?').run(id, guildId);
  db.close();

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