import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

/**
 * GET /api/v1/auth/invite/[token]
 * Validate an invitation token (public endpoint)
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ token: string }> }
) {
  try {
    const { token } = await params

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

    if (!invitation) {
      return NextResponse.json(
        { error: 'Invalid or expired invitation' },
        { status: 404 }
      )
    }

    // Check if expired
    if (invitation.expiresAt < new Date()) {
      return NextResponse.json(
        { error: 'This invitation has expired' },
        { status: 410 }
      )
    }

    // Check if email is already registered
    const existingStaff = await prisma.staff.findUnique({
      where: { email: invitation.email },
    })

    if (existingStaff) {
      return NextResponse.json(
        { error: 'An account with this email already exists' },
        { status: 409 }
      )
    }

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

    return NextResponse.json({
      valid: true,
      email: invitation.email,
      role: invitation.role,
      expiresAt: invitation.expiresAt,
      invitedBy: inviter?.name || 'Unknown',
    })
  } catch (error) {
    console.error('Error validating invitation:', error)
    return NextResponse.json(
      { error: 'Failed to validate invitation' },
      { status: 500 }
    )
  }
}
