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 GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify JWT token
    const decoded = verifyToken(request)
    if (!decoded) {
      return NextResponse.json(
        { message: 'Unauthorized' },
        { status: 401 }
      )
    }

    const { id } = await params

    // Get service request with all related data
    const serviceRequest = await db.serviceRequest.findUnique({
      where: { id },
      include: {
        service: {
          select: {
            title: true,
            slug: true
          }
        },
        user: {
          select: {
            name: true,
            email: true
          }
        }
      }
    })

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

    // Parse statusLog to ensure it's always an array
    let statusLog = []
    if (serviceRequest.statusLog) {
      try {
        if (Array.isArray(serviceRequest.statusLog)) {
          statusLog = serviceRequest.statusLog
        } else if (typeof serviceRequest.statusLog === 'string') {
          statusLog = JSON.parse(serviceRequest.statusLog)
        } else {
          statusLog = [serviceRequest.statusLog]
        }
      } catch (error) {
        console.error('Error parsing statusLog:', error)
        statusLog = []
      }
    }

    return NextResponse.json({
      id: serviceRequest.id,
      trackingNumber: serviceRequest.trackingNumber,
      service: serviceRequest.service,
      user: serviceRequest.user,
      status: serviceRequest.status,
      submissionData: serviceRequest.submissionData,
      statusLog,
      signatureUrl: serviceRequest.signatureUrl,
      photoUrl: serviceRequest.photoUrl,
      createdAt: serviceRequest.createdAt.toISOString(),
      updatedAt: serviceRequest.updatedAt.toISOString()
    })
  } catch (error) {
    console.error('Request detail API error:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}

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

    const { id } = await params

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

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

    // Delete the service request
    await db.serviceRequest.delete({
      where: { id }
    })

    return NextResponse.json({
      message: 'Pengajuan berhasil dihapus'
    })
  } catch (error) {
    console.error('Delete request API error:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}