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"
import { DEFAULT_TENANT_ID } from "@/lib/constants"

export const runtime = "nodejs"

const schema = z.object({
  machineId: z.string().min(1),
  persona: z.enum(["collaborator", "manager"]),
  email: z.string().email(),
  name: z.string().optional(),
})

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 schema>
  try {
    const body = await request.json()
    parsed = schema.parse(body)
  } 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 {
    const machine = (await client.query(api.machines.getContext, {
      machineId: parsed.machineId as Id<"machines">,
    })) as {
      id: string
      tenantId: string
      companyId: string | null
    } | null

    if (!machine) {
      return NextResponse.json({ error: "Máquina não encontrada" }, { status: 404 })
    }

    const tenantId = machine.tenantId ?? session.user.tenantId ?? DEFAULT_TENANT_ID

    const ensuredUser = (await client.mutation(api.users.ensureUser, {
      tenantId,
      email: parsed.email,
      name: parsed.name ?? parsed.email,
      avatarUrl: undefined,
      role: parsed.persona.toUpperCase(),
      companyId: machine.companyId ? (machine.companyId as Id<"companies">) : undefined,
    })) as { _id?: Id<"users"> } | null

    await client.mutation(api.machines.updatePersona, {
      machineId: parsed.machineId as Id<"machines">,
      persona: parsed.persona,
      assignedUserId: ensuredUser?._id,
      assignedUserEmail: parsed.email,
      assignedUserName: parsed.name ?? undefined,
      assignedUserRole: parsed.persona === "manager" ? "MANAGER" : "COLLABORATOR",
    })

    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error("[machines.access]", error)
    return NextResponse.json({ error: "Falha ao atualizar acesso da máquina" }, { status: 500 })
  }
}
