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

export async function GET(request: NextRequest) {
  try {
    const session = await auth()

    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized - Admin only' },
        { status: 403 }
      )
    }

    const searchParams = request.nextUrl.searchParams
    const page = parseInt(searchParams.get('page') || '1')
    const limit = Math.min(parseInt(searchParams.get('limit') || '30'), 50) // Max 50
    const search = searchParams.get('search') || ''
    const cursor = searchParams.get('cursor') || ''

    const offset = (page - 1) * limit

    // Build where condition
    const where = search
      ? {
          OR: [
            { slug: { contains: search } },
            { title: { contains: search } },
            { user: { email: { contains: search } } },
            { user: { name: { contains: search } } },
          ],
        }
      : {}

    // Get total count
    const totalCount = await prisma.microsite.count({ where })

    // Get microsites - use cursor if available for better performance
    let microsites
    if (cursor && !search) {
      microsites = await prisma.microsite.findMany({
        where: {
          ...where,
          id: { lt: cursor }
        },
        take: limit + 1,
        orderBy: { createdAt: 'desc' },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
          links: {
            select: {
              id: true,
              label: true,
              url: true,
              order: true,
              clicks: true,
            },
            orderBy: { order: 'asc' },
            take: 10, // Limit links per microsite for performance
          },
          _count: {
            select: {
              links: true,
            },
          },
        },
      })
    } else {
      microsites = await prisma.microsite.findMany({
        where,
        skip: offset,
        take: limit + 1,
        orderBy: { createdAt: 'desc' },
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
          links: {
            select: {
              id: true,
              label: true,
              url: true,
              order: true,
              clicks: true,
            },
            orderBy: { order: 'asc' },
            take: 10, // Limit links per microsite for performance
          },
          _count: {
            select: {
              links: true,
            },
          },
        },
      })
    }

    // Check if has more
    const hasMore = microsites.length > limit
    if (hasMore) microsites = microsites.slice(0, limit)

    // Get next cursor
    const nextCursor = microsites.length > 0 ? microsites[microsites.length - 1].id : null

    // Calculate total clicks for each microsite
    const formattedMicrosites = microsites.map(site => ({
      id: site.id,
      slug: site.slug,
      title: site.title,
      bio: site.bio,
      profilePicture: site.profilePicture,
      theme: site.theme,
      hasPassword: !!site.password,
      createdAt: site.createdAt,
      updatedAt: site.updatedAt,
      user: site.user,
      links: site.links,
      linksCount: site._count.links,
      totalClicks: site.links.reduce((sum, link) => sum + link.clicks, 0),
    }))

    return NextResponse.json({
      success: true,
      data: {
        microsites: formattedMicrosites,
        pagination: {
          page,
          limit,
          total: totalCount,
          totalPages: Math.ceil(totalCount / limit),
          hasMore,
          nextCursor,
        },
      },
    })
  } catch (error) {
    console.error('Admin microsites error:', error)
    return NextResponse.json(
      { success: false, error: `Failed to fetch microsites: ${error instanceof Error ? error.message : String(error)}` },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const session = await auth()

    if (!session?.user?.email || !isAdmin(session.user.email)) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized - Admin only' },
        { status: 403 }
      )
    }

    const { ids } = await request.json()

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return NextResponse.json(
        { success: false, error: 'No IDs provided' },
        { status: 400 }
      )
    }

    // Delete microsites (cascade will delete links)
    await prisma.microsite.deleteMany({
      where: {
        id: { in: ids },
      },
    })

    return NextResponse.json({
      success: true,
      message: `${ids.length} microsite(s) deleted`,
    })
  } catch (error) {
    console.error('Admin delete microsites error:', error)
    return NextResponse.json(
      { success: false, error: `Failed to delete microsites: ${error instanceof Error ? error.message : String(error)}` },
      { status: 500 }
    )
  }
}
