import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { generateTrackingNumber } from '@/lib/tracking-number'

export async function POST(request: NextRequest) {
  try {
    const { serviceSlug, submissionData } = await request.json()

    if (!serviceSlug || !submissionData) {
      return NextResponse.json(
        { message: 'Data tidak lengkap' },
        { status: 400 }
      )
    }

    // Find the service
    const service = await db.service.findUnique({
      where: { slug: serviceSlug }
    })

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

    // Generate tracking number based on service category
    const trackingNumber = await generateTrackingNumber(serviceSlug)

    // Create or find user (for demo purposes, we'll create a simple user)
    let user = await db.user.findFirst({
      where: { email: submissionData.email || 'user@example.com' }
    })

    if (!user) {
      user = await db.user.create({
        data: {
          name: submissionData.fullName || 'Anonymous User',
          email: submissionData.email || 'user@example.com',
          password: 'default_password', // In production, this should be properly handled
          role: 'USER'
        }
      })
    }

    // Create service request
    const serviceRequest = await db.serviceRequest.create({
      data: {
        userId: user.id,
        serviceId: service.id,
        trackingNumber,
        status: 'PENDING',
        submissionData,
        statusLog: [
          {
            status: 'PENDING',
            timestamp: new Date().toISOString(),
            message: 'Permohonan berhasil diajukan dan menunggu verifikasi'
          }
        ]
      }
    })

    return NextResponse.json({
      message: 'Pengajuan berhasil',
      trackingNumber: serviceRequest.trackingNumber,
      requestId: serviceRequest.id
    })
  } catch (error) {
    console.error('Error creating service request:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}