import jwt from 'jsonwebtoken'
import { db } from './db'
import { NextRequest } from 'next/server'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'

export async function verifyAdminToken(request: NextRequest) {
  const authHeader = request.headers.get('authorization')
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return { success: false, error: 'Token tidak ditemukan' }
  }

  const token = authHeader.substring(7)
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as any
    
    // Verify the user exists in database
    const admin = await db.admin.findUnique({
      where: { id: decoded.userId },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        isActive: true
      }
    })

    if (!admin || !admin.isActive) {
      return { success: false, error: 'Token tidak valid' }
    }

    return { success: true, admin }
  } catch (error) {
    return { success: false, error: 'Token tidak valid' }
  }
}