import { NextRequest, NextResponse } from 'next/server'
import { requireStaffPermission } from '@/lib/auth-helpers'
import { prisma } from '@/lib/prisma'
import { StaffStatus, Prisma } from '@prisma/client'

/**
 * GET /api/v1/admin/staff
 * List all staff members
 * Requires: staff:view permission
 */
export async function GET(request: NextRequest) {
  try {
    const session = await requireStaffPermission('staff:view')
    const currentUserId = session.user.id

    const searchParams = request.nextUrl.searchParams
    const status = searchParams.get('status') as StaffStatus | null
    const search = searchParams.get('search')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '50')

    const where: Prisma.StaffWhereInput = {}

    if (status) {
      where.status = status
    }

    if (search) {
      where.OR = [
        { email: { contains: search, mode: 'insensitive' } },
        { name: { contains: search, mode: 'insensitive' } },
      ]
    }

    const [staff, total] = await Promise.all([
      prisma.staff.findMany({
        where,
        select: {
          id: true,
          email: true,
          name: true,
          role: true,
          status: true,
          invitedBy: true,
          twoFactorEnabled: true,
          createdAt: true,
          updatedAt: true,
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      prisma.staff.count({ where }),
    ])

    // Get inviter names for staff who were invited
    const inviterIds = staff
      .map((s) => s.invitedBy)
      .filter((id): id is string => id !== null)

    const inviters = await prisma.staff.findMany({
      where: { id: { in: inviterIds } },
      select: { id: true, name: true, email: true },
    })

    const inviterMap = new Map(inviters.map((i) => [i.id, i]))

    const staffWithInviter = staff.map((s) => ({
      ...s,
      isCurrentUser: s.id === currentUserId,
      invitedByStaff: s.invitedBy ? inviterMap.get(s.invitedBy) || null : null,
    }))

    return NextResponse.json({
      staff: staffWithInviter,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    })
  } catch (error) {
    if (typeof error === 'object' && error !== null && 'status' in error) {
      const err = error as { status: number; message: string }
      return NextResponse.json({ error: err.message }, { status: err.status })
    }
    console.error('Error listing staff:', error)
    return NextResponse.json(
      { error: 'Failed to list staff' },
      { status: 500 }
    )
  }
}
