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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ trackingNumber: string }> }
) {
  try {
    const { trackingNumber } = await params

    const serviceRequest = await db.serviceRequest.findUnique({
      where: {
        trackingNumber: trackingNumber.toUpperCase()
      },
      include: {
        service: {
          select: {
            title: true
          }
        },
        user: {
          select: {
            name: true,
            email: true
          }
        }
      }
    })

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

    return NextResponse.json({
      id: serviceRequest.id,
      trackingNumber: serviceRequest.trackingNumber,
      service: serviceRequest.service,
      user: serviceRequest.user,
      status: serviceRequest.status,
      createdAt: serviceRequest.createdAt.toISOString(),
      statusLog: Array.isArray(serviceRequest.statusLog) ? serviceRequest.statusLog : [],
      submissionData: serviceRequest.submissionData,
      signatureUrl: serviceRequest.signatureUrl,
      photoUrl: serviceRequest.photoUrl
    })
  } catch (error) {
    console.error('Error tracking request:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}