import { auth } from '@/auth'
import { db } from '@/lib/db'
import { groups } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { NextRequest, NextResponse } from 'next/server'

type AuthUser = { id: string; role?: string }

export async function GET() {
  const authSession = await auth()
  if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const list = await db.select().from(groups).orderBy(groups.name)
  return NextResponse.json({ groups: list })
}

export async function POST(request: NextRequest) {
  const authSession = await auth()
  if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  const u = authSession.user as AuthUser
  if (u.role !== 'admin') return NextResponse.json({ error: 'Admin only' }, { status: 403 })

  const { name, description } = await request.json()
  if (!name?.trim()) return NextResponse.json({ error: 'Name required' }, { status: 400 })

  const [group] = await db.insert(groups).values({
    name: String(name).slice(0, 100),
    description: description ? String(description).slice(0, 500) : null,
    createdBy: u.id,
  }).returning()

  return NextResponse.json({ group })
}

export async function DELETE(request: NextRequest) {
  const authSession = await auth()
  if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  const u = authSession.user as AuthUser
  if (u.role !== 'admin') return NextResponse.json({ error: 'Admin only' }, { status: 403 })

  const { id } = await request.json()
  await db.delete(groups).where(eq(groups.id, id))
  return NextResponse.json({ success: true })
}
