import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { verifyAdminToken } from '@/lib/admin-auth'
import { writeFile, mkdir, unlink } from 'fs/promises'
import path from 'path'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    const socialMedia = await db.socialMedia.findUnique({
      where: { id }
    })

    if (!socialMedia) {
      return NextResponse.json(
        { success: false, message: 'Social media not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({
      success: true,
      data: socialMedia
    })
  } catch (error) {
    console.error('Error fetching social media:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to fetch social media' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    const formData = await request.formData()
    
    const platform = formData.get('platform') as string
    const name = formData.get('name') as string
    const url = formData.get('url') as string
    const username = formData.get('username') as string
    const description = formData.get('description') as string
    const isActive = formData.get('isActive') === 'true'
    const order = parseInt(formData.get('order') as string) || 0

    const iconFile = formData.get('icon') as File

    if (!platform || !name || !url) {
      return NextResponse.json(
        { success: false, message: 'Platform, name, and URL are required' },
        { status: 400 }
      )
    }

    // Validate platform
    const validPlatforms = ['FACEBOOK', 'INSTAGRAM', 'TWITTER', 'YOUTUBE', 'TIKTOK', 'LINKEDIN', 'WHATSAPP', 'TELEGRAM']
    if (!validPlatforms.includes(platform.toUpperCase())) {
      return NextResponse.json(
        { success: false, message: 'Invalid platform' },
        { status: 400 }
      )
    }

    // Get existing social media
    const existingSocialMedia = await db.socialMedia.findUnique({
      where: { id }
    })

    if (!existingSocialMedia) {
      return NextResponse.json(
        { success: false, message: 'Social media not found' },
        { status: 404 }
      )
    }

    // Check if social media with same platform and name already exists (excluding current record)
    const duplicateSocialMedia = await db.socialMedia.findFirst({
      where: {
        platform: platform.toUpperCase(),
        name,
        id: { not: id }
      }
    })

    if (duplicateSocialMedia) {
      return NextResponse.json(
        { success: false, message: 'Social media with this platform and name already exists' },
        { status: 400 }
      )
    }

    // Handle file upload
    let iconPath = existingSocialMedia.icon

    if (iconFile && iconFile.size > 0) {
      // Delete old icon if exists
      if (existingSocialMedia.icon) {
        try {
          await unlink(path.join(process.cwd(), 'public', existingSocialMedia.icon))
        } catch (error) {
          console.error('Error deleting old icon:', error)
        }
      }

      const bytes = await iconFile.arrayBuffer()
      const buffer = Buffer.from(bytes)
      
      const uploadsDir = path.join(process.cwd(), 'public', 'uploads', 'social-media')
      await mkdir(uploadsDir, { recursive: true })
      
      const filename = `${Date.now()}-${iconFile.name}`
      iconPath = `/uploads/social-media/${filename}`
      
      await writeFile(path.join(uploadsDir, filename), buffer)
    }

    const socialMedia = await db.socialMedia.update({
      where: { id },
      data: {
        platform: platform.toUpperCase() as any,
        name,
        url,
        username: username || null,
        description: description || null,
        icon: iconPath,
        isActive,
        order
      }
    })

    return NextResponse.json({
      success: true,
      message: 'Social media updated successfully',
      data: socialMedia
    })
  } catch (error) {
    console.error('Error updating social media:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to update social media' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    const socialMedia = await db.socialMedia.findUnique({
      where: { id }
    })

    if (!socialMedia) {
      return NextResponse.json(
        { success: false, message: 'Social media not found' },
        { status: 404 }
      )
    }

    // Delete associated file
    if (socialMedia.icon) {
      try {
        await unlink(path.join(process.cwd(), 'public', socialMedia.icon))
      } catch (error) {
        console.error('Error deleting icon:', error)
      }
    }

    await db.socialMedia.delete({
      where: { id }
    })

    return NextResponse.json({
      success: true,
      message: 'Social media deleted successfully'
    })
  } catch (error) {
    console.error('Error deleting social media:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to delete social media' },
      { status: 500 }
    )
  }
}