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

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

    const templates = await db.serviceTemplate.findMany({
      where,
      include: {
        service: {
          select: {
            id: true,
            title: true,
            slug: true,
            category: true
          }
        }
      },
      orderBy: { updatedAt: 'desc' }
    })

    return NextResponse.json({
      success: true,
      templates
    })
  } catch (error) {
    console.error('Error fetching templates:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat mengambil data template' },
      { 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 { serviceId, templateContent } = body

    // Validate required fields
    if (!serviceId || !templateContent) {
      return NextResponse.json(
        { error: 'Layanan dan konten template wajib diisi' },
        { status: 400 }
      )
    }

    // Check if service exists
    const service = await db.service.findUnique({
      where: { id: serviceId }
    })

    if (!service) {
      return NextResponse.json(
        { error: 'Layanan tidak ditemukan' },
        { status: 404 }
      )
    }

    // Check if template already exists for this service
    const existingTemplate = await db.serviceTemplate.findFirst({
      where: { serviceId }
    })

    if (existingTemplate) {
      return NextResponse.json(
        { error: 'Template untuk layanan ini sudah ada. Silakan edit template yang ada.' },
        { status: 400 }
      )
    }

    const template = await db.serviceTemplate.create({
      data: {
        serviceId,
        templateContent
      },
      include: {
        service: {
          select: {
            id: true,
            title: true,
            slug: true,
            category: true
          }
        }
      }
    })

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