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

    // Get dashboard statistics
    const [
      totalRequests,
      pendingRequests,
      inProgressRequests,
      completedRequests,
      totalUsers,
      recentRequests
    ] = await Promise.all([
      db.serviceRequest.count(),
      db.serviceRequest.count({ where: { status: 'PENDING' } }),
      db.serviceRequest.count({ where: { status: 'IN_PROGRESS' } }),
      db.serviceRequest.count({ where: { status: 'COMPLETED' } }),
      db.user.count(),
      db.serviceRequest.findMany({
        take: 5,
        orderBy: { createdAt: 'desc' },
        include: {
          service: {
            select: { title: true }
          },
          user: {
            select: { name: true }
          }
        }
      })
    ])

    return NextResponse.json({
      totalRequests,
      pendingRequests,
      inProgressRequests,
      completedRequests,
      totalUsers,
      recentRequests: recentRequests.map(req => ({
        ...req,
        createdAt: req.createdAt.toISOString(),
        // Ensure statusLog is always an array
        statusLog: Array.isArray(req.statusLog) ? req.statusLog : []
      }))
    })
  } catch (error) {
    console.error('Dashboard API error:', error)
    return NextResponse.json(
      { message: 'Terjadi kesalahan server' },
      { status: 500 }
    )
  }
}