import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { verifyAdminToken } from '@/lib/admin-auth'

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 status = searchParams.get('status')
    const category = searchParams.get('category')
    const search = searchParams.get('search')

    // Build where clause
    const where: any = {}
    
    if (status && status !== 'all') {
      where.status = status
    }
    
    if (category && category !== 'all') {
      where.category = category
    }
    
    if (search) {
      where.OR = [
        { title: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } }
      ]
    }

    const services = await db.service.findMany({
      where,
      include: {
        children: {
          where: { status: 'ACTIVE' },
          orderBy: { position: 'asc' }
        }
      },
      orderBy: [
        { position: 'asc' },
        { updatedAt: 'desc' }
      ]
    })

    // Clean invalid iconUrls
    const cleanedServices = services.map(service => {
      if (service.iconUrl && (!service.iconUrl.startsWith('/') && !service.iconUrl.startsWith('http'))) {
        return { ...service, iconUrl: null }
      }
      return service
    })

    return NextResponse.json({
      success: true,
      services: cleanedServices
    })
  } catch (error) {
    console.error('Error fetching services:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat mengambil data layanan' },
      { 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 body = await request.json()
    const { 
      title, 
      description, 
      category, 
      estimatedTime, 
      requirements, 
      iconUrl, 
      linkType, 
      linkUrl, 
      isNewTab, 
      status,
      parentId,
      position
    } = body

    // Validate required fields
    if (!title || !description) {
      return NextResponse.json(
        { error: 'Nama layanan dan deskripsi wajib diisi' },
        { status: 400 }
      )
    }

    // Validate linkType and parentId combination
    if (linkType === 'SUBMENU' && parentId) {
      // Child submenu with linkType SUBMENU should have children or linkUrl
      if (!linkUrl) {
        // It's okay - can be a grouping submenu without action
      }
    }

    // Validate external link
    if (linkType === 'EXTERNAL' && linkUrl) {
      // Support multiple URL schemes: http, https, tel, mailto, sms, whatsapp, etc.
      const validSchemes = [
        'http://',
        'https://',
        'tel:',
        'mailto:',
        'sms:',
        'whatsapp:',
        'wa.me/',
        'ftp://',
        'file://',
        'javascript:',
        'callto:'
      ]
      
      const isValidUrl = validSchemes.some(scheme => linkUrl.startsWith(scheme))
      
      if (!isValidUrl) {
        return NextResponse.json(
          { 
            error: 'Link eksternal harus dimulai dengan salah satu: http://, https://, tel:, mailto:, sms:, whatsapp:, wa.me/, ftp://, file://, javascript:, atau callto:' 
          },
          { status: 400 }
        )
      }
    }

    // Generate slug from title
    const slug = title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')

    // Check if slug already exists
    const existingService = await db.service.findUnique({
      where: { slug }
    })

    if (existingService) {
      return NextResponse.json(
        { error: 'Layanan dengan nama serupa sudah ada' },
        { status: 400 }
      )
    }

    // Get the next position if not provided
    let nextPosition = position || 0
    if (!position) {
      const lastService = await db.service.findFirst({
        where: { parentId: parentId || null },
        orderBy: { position: 'desc' }
      })
      nextPosition = (lastService?.position || 0) + 1
    }

    const service = await db.service.create({
      data: {
        title,
        slug,
        description,
        category: category || 'lainnya',
        estimatedTime: estimatedTime || '',
        requirements: requirements || [],
        iconUrl: iconUrl || null,
        linkType: linkType || 'INTERNAL',
        linkUrl: linkUrl || null,
        isNewTab: isNewTab || false,
        status: status || 'ACTIVE',
        parentId: parentId || null,
        position: nextPosition
      }
    })

    return NextResponse.json({
      success: true,
      service,
      message: 'Layanan berhasil ditambahkan'
    })
  } catch (error) {
    console.error('Error creating service:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat menambah layanan' },
      { status: 500 }
    )
  }
}