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

// GET a specific microsite by slug
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params

    const microsite = await prisma.microsite.findUnique({
      where: { slug },
      include: {
        user: {
          select: {
            name: true,
            email: true,
            image: true,
          },
        },
        links: {
          orderBy: {
            order: 'asc',
          },
          include: {
            shortLink: true,
          },
        },
      },
    })

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

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

// PUT update microsite
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const session = await auth()

  if (!session?.user?.id) {
    return NextResponse.json(
      { success: false, error: 'Unauthorized' },
      { status: 401 }
    )
  }

  const { slug } = await params

  try {
    const body = await request.json()
    console.log('Request body size:', JSON.stringify(body).length, 'bytes')

    interface LinkInput {
      label: string
      url: string
      shortLinkId?: bigint | null
    }
    const { title, bio, profilePicture, theme, password, links } = body as {
      title: string
      bio?: string
      profilePicture?: string
      theme?: string
      password?: string
      links?: LinkInput[]
    }

    // Validate profile picture if provided
    if (profilePicture) {
      // Check if it's a valid data URL
      if (!profilePicture.startsWith('data:image/')) {
        return NextResponse.json(
          { success: false, error: 'Format gambar tidak valid. Harap unggah gambar kembali.' },
          { status: 400 }
        )
      }

      // Check estimated size
      const base64Data = profilePicture.split(',')[1]
      if (base64Data) {
        const estimatedSize = base64Data.length * 0.75
        console.log('Profile picture estimated size:', estimatedSize, 'bytes')
        if (estimatedSize > 500 * 1024) {
          return NextResponse.json(
            { success: false, error: 'Gambar profil terlalu besar. Maksimal ukuran adalah 500KB.' },
            { status: 400 }
          )
        }
      }
    }

    // Check ownership
    const existingMicrosite = await prisma.microsite.findUnique({
      where: { slug },
    })

    if (!existingMicrosite || existingMicrosite.userId !== session.user.id) {
      return NextResponse.json(
        { success: false, error: 'Not authorized to edit this microsite' },
        { status: 403 }
      )
    }

    // Hash password if provided
    let hashedPassword = existingMicrosite.password
    if (password !== undefined) {
      hashedPassword = password ? await bcrypt.hash(password, 10) : null
    }

    console.log('Starting database operations for microsite:', slug)

    // Delete existing links and create new ones
    console.log('Deleting existing links...')
    await prisma.micrositeLink.deleteMany({
      where: { micrositeId: existingMicrosite.id },
    })

    console.log('Preparing update data...')

    // Validate links data
    const validatedLinks = links?.filter(link => {
      if (!link.label || !link.url) {
        console.warn('Skipping invalid link:', { label: link.label, url: link.url })
        return false
      }
      return true
    }).map((link: LinkInput, index: number) => ({
      label: link.label.substring(0, 100), // Limit label length
      url: link.url.substring(0, 2048), // Limit URL length
      order: index,
      shortLinkId: link.shortLinkId || null,
    })) || []

    console.log('Validated links count:', validatedLinks.length)

    const updateData = {
      title: title.substring(0, 100), // Limit title length
      bio: bio ? bio.substring(0, 500) : null, // Limit bio length
      profilePicture: profilePicture || null,
      theme: theme || 'default',
      password: hashedPassword,
      links: {
        create: validatedLinks,
      },
    }

    console.log('Profile picture size for update:', profilePicture ? profilePicture.length : 0)
    console.log('Number of links to create:', updateData.links.create.length)

    // Update microsite
    console.log('Updating microsite...')
    const microsite = await prisma.microsite.update({
      where: { slug },
      data: updateData,
      include: {
        links: true,
      },
    })

    return NextResponse.json({ success: true, data: microsite })
  } catch (error) {
    console.error('Error updating microsite:', error)

    // More specific error messages
    let errorMessage = 'Gagal memperbarui microsite. Silakan coba lagi.'

    if (error instanceof Error) {
      console.error('Error details:', {
        message: error.message,
        name: error.name,
        slug: slug
      })

      // Check for various error patterns
      const message = error.message.toLowerCase()

      if (message.includes('data too long') || message.includes('1406')) {
        errorMessage = 'Gambar profil terlalu besar untuk database. Silakan pilih gambar yang lebih kecil (maksimal 1MB).'
      } else if (message.includes('invalid url') || message.includes('url validation')) {
        errorMessage = 'Format URL pada link tidak valid. Pastikan URL dimulai dengan http:// atau https://'
      } else if (message.includes('unique constraint') || message.includes('duplicate')) {
        errorMessage = 'Terjadi kesalahan pada database. Silakan coba lagi dengan data yang berbeda.'
      } else if (message.includes('prisma') || message.includes('database')) {
        errorMessage = 'Terjadi kesalahan pada database: ' + error.message.substring(0, 150) + '...'
      } else if (message.includes('json') || message.includes('parse')) {
        errorMessage = 'Terjadi kesalahan pada data yang dikirim. Silakan refresh halaman dan coba lagi.'
      } else if (message.includes('enotfound') || message.includes('network')) {
        errorMessage = 'Terjadi kesalahan jaringan. Silakan periksa koneksi internet Anda.'
      } else if (message.includes('timeout')) {
        errorMessage = 'Request terlalu lama. Silakan coba lagi dengan gambar yang lebih kecil.'
      } else {
        // Log the actual error for debugging
        console.error('Unhandled error:', {
          message: error.message,
          stack: error.stack,
          slug: slug
        })
        errorMessage = `Terjadi kesalahan: ${error.message.substring(0, 100)}. Silakan coba lagi.`
      }
    } else {
      console.error('Unknown error type:', error)
      errorMessage = 'Terjadi kesalahan yang tidak diketahui. Silakan refresh halaman dan coba lagi.'
    }

    return NextResponse.json(
      { success: false, error: errorMessage },
      { status: 500 }
    )
  }
}

// DELETE microsite
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const session = await auth()

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const { slug } = await params

    // Check ownership
    const microsite = await prisma.microsite.findUnique({
      where: { slug },
    })

    if (!microsite || microsite.userId !== session.user.id) {
      return NextResponse.json(
        { success: false, error: 'Not authorized to delete this microsite' },
        { status: 403 }
      )
    }

    await prisma.microsite.delete({
      where: { slug },
    })

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