import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import jwt from 'jsonwebtoken'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'

// Middleware to verify JWT token
function verifyToken(request: NextRequest) {
  const authHeader = request.headers.get('authorization')
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null
  }

  const token = authHeader.substring(7)
  try {
    return jwt.verify(token, JWT_SECRET) as any
  } catch (error) {
    return null
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // Verify JWT token
    const decoded = verifyToken(request)
    if (!decoded) {
      return NextResponse.json(
        { message: 'Unauthorized' },
        { status: 401 }
      )
    }

    const { id } = params
    const { status, message } = await request.json()

    if (!status) {
      return NextResponse.json(
        { message: 'Status harus diisi' },
        { status: 400 }
      )
    }

    // Get current request and admin user info
    const [currentRequest, adminUser] = await Promise.all([
      db.serviceRequest.findUnique({
        where: { id },
        include: {
          user: {
            select: { name: true }
          }
        }
      }),
      db.admin.findUnique({
        where: { id: decoded.userId },
        select: { name: true }
      })
    ])

    if (!currentRequest) {
      return NextResponse.json(
        { message: 'Pengajuan tidak ditemukan' },
        { status: 404 }
      )
    }

    if (!adminUser) {
      return NextResponse.json(
        { message: 'Admin tidak ditemukan' },
        { status: 404 }
      )
    }

    // Get current status log or create new array
    const currentLog = currentRequest.statusLog as Array<any> || []
    
    // Add new status log entry
    const newLogEntry = {
      status,
      timestamp: new Date().toISOString(),
      message: message || getDefaultStatusMessage(status),
      adminName: adminUser.name
    }

    // Update request with new status and log
    const updatedRequest = await db.serviceRequest.update({
      where: { id },
      data: {
        status,
        statusLog: [...currentLog, newLogEntry]
      }
    })

    return NextResponse.json({
      message: 'Status berhasil diperbarui',
      status: updatedRequest.status,
      statusLog: updatedRequest.statusLog
    })
  } catch (error) {
    console.error('Status update API error:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}

function getDefaultStatusMessage(status: string): string {
  switch (status) {
    case 'PENDING':
      return 'Permohonan sedang menunggu verifikasi'
    case 'IN_PROGRESS':
      return 'Permohonan sedang diproses oleh admin'
    case 'NEED_REVISION':
      return 'Admin meminta Anda untuk menyediakan foto dan/atau tanda tangan.'
    case 'REVIEWING':
      return 'Permohonan sedang dalam tahap peninjauan final'
    case 'COMPLETED':
      return 'Permohonan telah selesai diproses'
    default:
      return 'Status telah diperbarui'
  }
}