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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { auth } = await import('@/lib/auth')
    const { isAdmin } = await import('@/lib/admin')

    const session = await auth()
    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Admin access required' },
        { status: 403 }
      )
    }

    const { id } = await params

    // Get short link
    const shortLink = await prisma.shortLink.findFirst({
      where: {
        id: BigInt(id)
      }
    })

    if (!shortLink) {
      return NextResponse.json(
        { success: false, error: 'Short link not found' },
        { status: 404 }
      )
    }

    // Convert BigInt to string and format dates
    const formattedLink = {
      id: shortLink.id.toString(),
      code: shortLink.code,
      link: shortLink.link,
      clicks: 0, // No clicks field in ShortLink model
      createdAt: shortLink.createdAt.toISOString(),
      updatedAt: shortLink.updatedAt.toISOString(),
      deletedAt: shortLink.deletedAt?.toISOString() || null
    }

    return NextResponse.json({
      success: true,
      data: formattedLink
    })

  } catch (error) {
    console.error('Error fetching short link details:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to fetch short link details' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { auth } = await import('@/lib/auth')
    const { isAdmin } = await import('@/lib/admin')

    const session = await auth()
    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Admin access required' },
        { status: 403 }
      )
    }

    const { id } = await params

    // Soft delete the short link
    const deletedLink = await prisma.shortLink.update({
      where: {
        id: BigInt(id)
      },
      data: {
        deletedAt: new Date()
      }
    })

    return NextResponse.json({
      success: true,
      message: 'Short link deleted successfully'
    })

  } catch (error) {
    console.error('Error deleting short link:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to delete short link' },
      { status: 500 }
    )
  }
}