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

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 { services } = body

    // Validate input
    if (!Array.isArray(services)) {
      return NextResponse.json(
        { error: 'Format data tidak valid' },
        { status: 400 }
      )
    }

    // Validate each service item
    for (const item of services) {
      if (!item.id || typeof item.position !== 'number') {
        return NextResponse.json(
          { error: 'Setiap item harus memiliki id dan position yang valid' },
          { status: 400 }
        )
      }
    }

    // Update positions in a transaction
    await db.$transaction(async (tx) => {
      for (const item of services) {
        await tx.service.update({
          where: { id: item.id },
          data: { position: item.position }
        })
      }
    })

    return NextResponse.json({
      success: true,
      message: 'Urutan layanan berhasil diperbarui'
    })
  } catch (error) {
    console.error('Error reordering services:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat memperbarui urutan layanan' },
      { status: 500 }
    )
  }
}