import { auth } from '@/auth'
import { db } from '@/lib/db'
import { invites, users } from '@/lib/db/schema'
import { eq, and, isNull, gt } from 'drizzle-orm'
import { NextRequest, NextResponse } from 'next/server'

async function requireAdmin() {
  const session = await auth()
  if (!session?.user?.id) return null
  const role = (session.user as { role: string }).role
  if (role !== 'admin') return null
  return session.user
}

export async function POST(request: NextRequest) {
  const admin = await requireAdmin()
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { email } = await request.json()
  if (!email || typeof email !== 'string') {
    return NextResponse.json({ error: 'Valid email required' }, { status: 400 })
  }

  const normalizedEmail = email.toLowerCase().trim()

  // Check for existing pending invite
  const existing = await db
    .select({ id: invites.id })
    .from(invites)
    .where(
      and(
        eq(invites.email, normalizedEmail),
        isNull(invites.usedAt),
        gt(invites.expiresAt, new Date())
      )
    )
    .limit(1)

  if (existing.length > 0) {
    return NextResponse.json(
      { error: 'A pending invite already exists for this email' },
      { status: 409 }
    )
  }

  const result = await db
    .insert(invites)
    .values({ email: normalizedEmail, createdBy: admin.id })
    .returning()

  return NextResponse.json({ invite: result[0] }, { status: 201 })
}

export async function GET() {
  const admin = await requireAdmin()
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const result = await db
    .select()
    .from(invites)
    .orderBy(invites.createdAt)

  return NextResponse.json({ invites: result.reverse() })
}

export async function DELETE(request: NextRequest) {
  const admin = await requireAdmin()
  if (!admin) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const { id } = await request.json()
  if (!id) return NextResponse.json({ error: 'Invite ID required' }, { status: 400 })

  await db.delete(invites).where(eq(invites.id, id))

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