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 {
    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 permissions = await db.permission.findMany({
      orderBy: { createdAt: 'desc' }
    })

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

export async function POST(request: NextRequest) {
  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, description, module, action, isActive } = body

    // Validate required fields
    if (!name || !module || !action) {
      return NextResponse.json({ message: 'Name, module, and action are required' }, { status: 400 })
    }

    // Check if permission already exists
    const existingPermission = await db.permission.findFirst({
      where: { 
        name,
        module,
        action
      }
    })

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

    // Create new permission
    const newPermission = await db.permission.create({
      data: {
        name,
        description,
        module,
        action,
        isActive: isActive !== undefined ? isActive : true
      }
    })

    return NextResponse.json(newPermission, { status: 201 })
  } catch (error) {
    console.error('Error creating permission:', error)
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 })
  }
}