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

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

    const template = await db.serviceTemplate.findUnique({
      where: { id: params.id },
      include: {
        service: {
          select: {
            id: true,
            title: true,
            slug: true,
            category: true
          }
        }
      }
    })

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

    return NextResponse.json({
      success: true,
      template
    })
  } catch (error) {
    console.error('Error fetching template:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat mengambil data template' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  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 (!templateContent) {
      return NextResponse.json(
        { error: 'Konten template wajib diisi' },
        { status: 400 }
      )
    }

    // Check if template exists
    const existingTemplate = await db.serviceTemplate.findUnique({
      where: { id: params.id }
    })

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

    // If serviceId is being changed, validate it
    if (serviceId && serviceId !== existingTemplate.serviceId) {
      const service = await db.service.findUnique({
        where: { id: serviceId }
      })

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

      // Check if another template exists for the new service
      const conflictingTemplate = await db.serviceTemplate.findFirst({
        where: {
          serviceId,
          id: { not: params.id }
        }
      })

      if (conflictingTemplate) {
        return NextResponse.json(
          { error: 'Template untuk layanan ini sudah ada' },
          { status: 400 }
        )
      }
    }

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

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

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

    // Check if template exists
    const existingTemplate = await db.serviceTemplate.findUnique({
      where: { id: params.id }
    })

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

    await db.serviceTemplate.delete({
      where: { id: params.id }
    })

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