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

interface ShortLinkData {
  id: bigint
  code: string | null
  link: string | null
  createdAt: Date
  updatedAt: Date
  deletedAt: Date | null
}

// Helper to serialize BigInt to string for JSON
function serializeShortLink(link: ShortLinkData) {
  return {
    ...link,
    id: link.id.toString(),
  }
}

// DELETE (soft delete) a short link
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    // Convert string id to BigInt
    await prisma.shortLink.update({
      where: { id: BigInt(id) },
      data: { deletedAt: new Date() },
    })

    return NextResponse.json({ success: true, message: 'Link deleted successfully' })
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Failed to delete link' },
      { status: 500 }
    )
  }
}

// GET a short link by ID or code
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    let shortLink = null

    // Cek apakah id adalah numeric (BigInt) atau code (string)
    if (/^\d+$/.test(id)) {
      // Cari berdasarkan ID
      shortLink = await prisma.shortLink.findUnique({
        where: { id: BigInt(id) },
      })
    } else {
      // Cari berdasarkan code
      shortLink = await prisma.shortLink.findFirst({
        where: {
          code: id,
          deletedAt: null
        },
      })
    }

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

    return NextResponse.json({ success: true, data: serializeShortLink(shortLink) })
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Failed to fetch link' },
      { status: 500 }
    )
  }
}
