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

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

    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')
    const search = searchParams.get('search') || ''
    const platform = searchParams.get('platform')
    const isActive = searchParams.get('isActive')

    const skip = (page - 1) * limit

    const where: any = {}
    
    if (search) {
      where.OR = [
        { name: { contains: search, mode: 'insensitive' } },
        { username: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } }
      ]
    }

    if (platform) {
      where.platform = platform.toUpperCase()
    }

    if (isActive !== null && isActive !== undefined) {
      where.isActive = isActive === 'true'
    }

    const [socialMedia, total] = await Promise.all([
      db.socialMedia.findMany({
        where,
        orderBy: [
          { order: 'asc' },
          { platform: 'asc' },
          { name: 'asc' }
        ],
        skip,
        take: limit
      }),
      db.socialMedia.count({ where })
    ])

    return NextResponse.json({
      success: true,
      data: socialMedia,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    })
  } catch (error) {
    console.error('Error fetching social media:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to fetch social media data' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    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 }
      )
    }

    // Check if social media with same platform and name already exists
    const existingSocialMedia = await db.socialMedia.findFirst({
      where: {
        platform: platform.toUpperCase(),
        name
      }
    })

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

    // Handle file upload
    let iconPath = null

    if (iconFile && iconFile.size > 0) {
      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.create({
      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 created successfully',
      data: socialMedia
    })
  } catch (error) {
    console.error('Error creating social media:', error)
    return NextResponse.json(
      { success: false, message: 'Failed to create social media' },
      { status: 500 }
    )
  }
}