import { NextRequest, NextResponse } from "next/server"
import type { Id } from "@/convex/_generated/dataModel"
import { api } from "@/convex/_generated/api"
import { createConvexClient, ConvexConfigurationError } from "@/server/convex-client"

export const dynamic = "force-dynamic"

export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const client = createConvexClient()
    const { id } = await ctx.params
    const machineId = id as Id<"machines">
    const data = (await client.query(api.devices.getById, { id: machineId, includeMetadata: true })) as unknown
    if (!data) return NextResponse.json({ error: "Not found" }, { status: 404 })
    return NextResponse.json(data, { status: 200 })
  } catch (err) {
    if (err instanceof ConvexConfigurationError) {
      console.error("[api] admin/machines/[id]/details configuration error", err)
      return NextResponse.json({ error: err.message }, { status: 500 })
    }
    console.error("[api] admin/machines/[id]/details error", err)
    const message = err instanceof Error && err.message ? err.message : "Internal error"
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
