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 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 { permissionIds } = body

    if (!Array.isArray(permissionIds)) {
      return NextResponse.json({ message: 'Permission IDs must be an array' }, { status: 400 })
    }

    // Find the role
    const role = await db.systemRole.findUnique({
      where: { id: params.id }
    })

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

    // Delete existing role permissions
    await db.systemRolePermission.deleteMany({
      where: { roleId: params.id }
    })

    // Create new role permissions
    if (permissionIds.length > 0) {
      await db.systemRolePermission.createMany({
        data: permissionIds.map((permissionId: string) => ({
          roleId: params.id,
          permissionId
        }))
      })
    }

    // Fetch updated role with permissions
    const updatedRole = await db.systemRole.findUnique({
      where: { id: params.id },
      include: {
        permissions: {
          include: {
            permission: true
          }
        }
      }
    })

    // Transform the data to match expected format
    const transformedRole = {
      id: updatedRole.id,
      name: updatedRole.name,
      description: updatedRole.description,
      isActive: updatedRole.isActive,
      createdAt: updatedRole.createdAt,
      updatedAt: updatedRole.updatedAt,
      permissions: updatedRole.permissions.map(rp => rp.permission)
    }

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