import { NextRequest, NextResponse } from 'next/server'
import { getCurrentUser } from '@/lib/auth'
import { roleService } from '@/lib/services/role-service'
import { createAuditLog } from '@/lib/audit'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const currentUser = await getCurrentUser()
    if (!currentUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (!['ADMIN', 'SUPERADMIN'].includes(currentUser.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const role = await roleService.getRoleById(id)
    if (!role) {
      return NextResponse.json({ error: 'Role not found' }, { status: 404 })
    }

    return NextResponse.json({ role })
  } catch (error) {
    console.error('[API] Failed to fetch role:', error)
    return NextResponse.json({ error: 'Failed to fetch role' }, { status: 500 })
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const currentUser = await getCurrentUser()
    if (!currentUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (currentUser.role !== 'SUPERADMIN') {
      return NextResponse.json({ error: 'Only superadmins can update roles' }, { status: 403 })
    }

    const body = await request.json()
    const { displayName, description, color, priority, permissionIds } = body

    const role = await roleService.updateRole(id, {
      displayName,
      description,
      color,
      priority,
      permissionIds,
    })

    await createAuditLog({
      userId: currentUser.id,
      action: 'UPDATE_ROLE',
      category: 'ADMIN',
      details: { roleId: id, changes: body },
    })

    return NextResponse.json({ role })
  } catch (error) {
    console.error('[API] Failed to update role:', error)
    return NextResponse.json({ error: 'Failed to update role' }, { status: 500 })
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const currentUser = await getCurrentUser()
    if (!currentUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (currentUser.role !== 'SUPERADMIN') {
      return NextResponse.json({ error: 'Only superadmins can delete roles' }, { status: 403 })
    }

    const role = await roleService.getRoleById(id)
    if (!role) {
      return NextResponse.json({ error: 'Role not found' }, { status: 404 })
    }

    await roleService.deleteRole(id)

    await createAuditLog({
      userId: currentUser.id,
      action: 'DELETE_ROLE',
      category: 'ADMIN',
      details: { roleId: id, roleName: role.name },
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[API] Failed to delete role:', error)
    const message = error instanceof Error ? error.message : 'Failed to delete role'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
