import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import jwt from 'jsonwebtoken'
import { writeFile, mkdir } from 'fs/promises'
import { join } from 'path'

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 POST(
  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
    
    // Parse form data
    const formData = await request.formData()
    const file = formData.get('file') as File
    const type = formData.get('type') as string

    if (!file) {
      return NextResponse.json(
        { message: 'File harus diunggah' },
        { status: 400 }
      )
    }

    if (!type || !['photo', 'signature'].includes(type)) {
      return NextResponse.json(
        { message: 'Tipe file tidak valid' },
        { status: 400 }
      )
    }

    // Validate file type
    if (!file.type.startsWith('image/')) {
      return NextResponse.json(
        { message: 'Hanya file gambar yang diperbolehkan' },
        { status: 400 }
      )
    }

    // Validate file size (max 50MB)
    if (file.size > 50 * 1024 * 1024) {
      return NextResponse.json(
        { message: 'Ukuran file maksimal 50MB' },
        { status: 400 }
      )
    }

    // Get current request
    const currentRequest = await db.serviceRequest.findUnique({
      where: { id }
    })

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

    // Create uploads directory if it doesn't exist
    const uploadsDir = join(process.cwd(), 'public', 'uploads')
    try {
      await mkdir(uploadsDir, { recursive: true })
    } catch (error) {
      // Directory already exists
    }

    // Generate unique filename
    const timestamp = Date.now()
    const extension = file.name.split('.').pop()
    const filename = `${id}_${type}_${timestamp}.${extension}`
    const filepath = join(uploadsDir, filename)

    // Save file
    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)
    await writeFile(filepath, buffer)

    // Update request with file URL
    const updateData = type === 'photo' 
      ? { photoUrl: `/uploads/${filename}` }
      : { signatureUrl: `/uploads/${filename}` }

    // If uploading photo or signature, automatically change status to NEED_REVISION
    if (type === 'photo' || type === 'signature') {
      const currentLog = currentRequest.statusLog as Array<any> || []
      const adminUser = await db.admin.findUnique({
        where: { id: decoded.userId },
        select: { name: true }
      })

      const newLogEntry = {
        status: 'NEED_REVISION',
        timestamp: new Date().toISOString(),
        message: 'Admin meminta Anda untuk menyediakan foto dan/atau tanda tangan.',
        adminName: adminUser?.name || 'Admin'
      }

      updateData.status = 'NEED_REVISION'
      updateData.statusLog = [...currentLog, newLogEntry]
    }

    const updatedRequest = await db.serviceRequest.update({
      where: { id },
      data: updateData
    })

    return NextResponse.json({
      message: `${type === 'photo' ? 'Foto' : 'Tanda tangan'} berhasil diunggah`,
      url: `/uploads/${filename}`,
      request: {
        id: updatedRequest.id,
        status: updatedRequest.status,
        photoUrl: updatedRequest.photoUrl,
        signatureUrl: updatedRequest.signatureUrl
      }
    })
  } catch (error) {
    console.error('File upload API error:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}