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

/**
 * GET /api/v1/admin/staff/invites/[id]
 * Get invitation details
 * Requires: staff:view permission
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    await requireStaffPermission('staff:view')
    const { id } = await params

    const invitation = await prisma.staffInvitation.findUnique({
      where: { id },
      select: {
        id: true,
        email: true,
        role: true,
        expiresAt: true,
        invitedBy: true,
        createdAt: true,
      },
    })

    if (!invitation) {
      return NextResponse.json(
        { error: 'Invitation not found' },
        { status: 404 }
      )
    }

    // Get inviter details
    const inviter = await prisma.staff.findUnique({
      where: { id: invitation.invitedBy },
      select: { id: true, name: true, email: true },
    })

    return NextResponse.json({
      ...invitation,
      isExpired: invitation.expiresAt < new Date(),
      invitedByStaff: inviter,
    })
  } 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 getting invitation:', error)
    return NextResponse.json(
      { error: 'Failed to get invitation' },
      { status: 500 }
    )
  }
}

/**
 * DELETE /api/v1/admin/staff/invites/[id]
 * Cancel/delete a staff invitation
 * Requires: staff:invite permission
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    await requireStaffPermission('staff:invite')
    const { id } = await params

    // Check if invitation exists
    const invitation = await prisma.staffInvitation.findUnique({
      where: { id },
      select: { id: true, email: true },
    })

    if (!invitation) {
      return NextResponse.json(
        { error: 'Invitation not found' },
        { status: 404 }
      )
    }

    await prisma.staffInvitation.delete({
      where: { id },
    })

    return NextResponse.json({
      deleted: true,
      email: invitation.email,
    })
  } 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 deleting invitation:', error)
    return NextResponse.json(
      { error: 'Failed to delete invitation' },
      { status: 500 }
    )
  }
}
