import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { assertStaffSession } from "@/lib/auth-server"

export const runtime = "nodejs"

const addSchema = z.object({ machineId: z.string().min(1), email: z.string().email() })
const removeSchema = z.object({ machineId: z.string().min(1), userId: z.string().min(1) })

export async function POST(request: Request) {
  const session = await assertStaffSession()
  if (!session) return NextResponse.json({ error: "Não autorizado" }, { status: 401 })

  let parsed: z.infer<typeof addSchema>
  try {
    parsed = addSchema.parse(await request.json())
  } catch {
    return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
  }

  const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
  const client = new ConvexHttpClient(convexUrl)

  try {
    await client.mutation(api.devices.linkUser, {
      machineId: parsed.machineId as Id<"machines">,
      email: parsed.email,
    })
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error("[machines.links.add]", error)
    return NextResponse.json({ error: "Falha ao vincular usuário" }, { status: 500 })
  }
}

export async function DELETE(request: Request) {
  const session = await assertStaffSession()
  if (!session) return NextResponse.json({ error: "Não autorizado" }, { status: 401 })

  const url = new URL(request.url)
  const machineId = url.searchParams.get("machineId")
  const userId = url.searchParams.get("userId")
  const parsed = removeSchema.safeParse({ machineId, userId })
  if (!parsed.success) return NextResponse.json({ error: "Parâmetros inválidos" }, { status: 400 })

  const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
  const client = new ConvexHttpClient(convexUrl)

  try {
    await client.mutation(api.devices.unlinkUser, {
      machineId: parsed.data.machineId as Id<"machines">,
      userId: parsed.data.userId as Id<"users">,
    })
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error("[machines.links.remove]", error)
    return NextResponse.json({ error: "Falha ao desvincular usuário" }, { status: 500 })
  }
}

