import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'

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 PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const decoded = verifyToken(request)
    
    if (!decoded) {
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    // Verify admin is SUPERADMIN
    const admin = await db.admin.findUnique({
      where: { id: decoded.userId, isActive: true }
    })

    if (!admin || admin.role !== 'SUPERADMIN') {
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const { name, email, role, password, isActive } = body

    // Find the user to update
    const userToUpdate = await db.admin.findUnique({
      where: { id: params.id }
    })

    if (!userToUpdate) {
      return NextResponse.json({ message: 'User not found' }, { status: 404 })
    }

    // Check if email is being changed and if it already exists
    if (email !== userToUpdate.email) {
      const existingUser = await db.admin.findFirst({
        where: { email }
      })

      if (existingUser) {
        return NextResponse.json({ message: 'Email already exists' }, { status: 400 })
      }
    }

    // Prepare update data
    const updateData: any = {
      name,
      email,
      role,
      isActive
    }

    // Only update password if provided
    if (password && password.trim() !== '') {
      updateData.password = await bcrypt.hash(password, 10)
    }

    // Update user
    const updatedUser = await db.admin.update({
      where: { id: params.id },
      data: updateData,
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        isActive: true,
        lastLogin: true,
        createdAt: true,
        updatedAt: true
      }
    })

    return NextResponse.json(updatedUser)
  } catch (error) {
    console.error('Error updating user:', error)
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 })
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const decoded = verifyToken(request)
    
    if (!decoded) {
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    // Verify admin is SUPERADMIN
    const admin = await db.admin.findUnique({
      where: { id: decoded.userId, isActive: true }
    })

    if (!admin || admin.role !== 'SUPERADMIN') {
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    // Find the user to delete
    const userToDelete = await db.admin.findUnique({
      where: { id: params.id }
    })

    if (!userToDelete) {
      return NextResponse.json({ message: 'User not found' }, { status: 404 })
    }

    // Prevent self-deletion
    if (userToDelete.id === admin.id) {
      return NextResponse.json({ message: 'Cannot delete your own account' }, { status: 400 })
    }

    // Delete user
    await db.admin.delete({
      where: { id: params.id }
    })

    return NextResponse.json({ message: 'User deleted successfully' })
  } catch (error) {
    console.error('Error deleting user:', error)
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 })
  }
}