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

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

    return NextResponse.json(transformedRoles)
  } catch (error) {
    console.error('Error fetching roles:', 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, isActive } = body

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

    // Check if role already exists
    const existingRole = await db.systemRole.findFirst({
      where: { name }
    })

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

    // Create new role
    const newRole = await db.systemRole.create({
      data: {
        name,
        description,
        isActive: isActive !== undefined ? isActive : true
      },
      include: {
        permissions: {
          include: {
            permission: true
          }
        }
      }
    })

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

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