import { NextResponse } from "next/server"
import { requireAuth } from "@/lib/shared/middleware/auth.middleware"
import { withErrorHandling } from "@/lib/shared/middleware/errorHandler.middleware"
import {
  deleteRoleById,
  getRole,
  updateRoleFromRequest,
} from "@/lib/controllers/roleController"

export const runtime = "nodejs"

export const GET = withErrorHandling(
  async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
    const unauthorized = await requireAuth()
    if (unauthorized) return unauthorized

    const { id } = await params
    const role = await getRole(id)
    if (!role) {
      return NextResponse.json({ error: "Role not found" }, { status: 404 })
    }
    return NextResponse.json(role)
  }
)

export const PUT = withErrorHandling(
  async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
    const unauthorized = await requireAuth()
    if (unauthorized) return unauthorized

    const { id } = await params
    const role = await updateRoleFromRequest(req, id)
    return NextResponse.json(role)
  }
)

export const DELETE = withErrorHandling(
  async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
    const unauthorized = await requireAuth()
    if (unauthorized) return unauthorized

    const { id } = await params
    await deleteRoleById(id)
    return NextResponse.json({ success: true })
  }
)
