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

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

export const runtime = "nodejs"

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

  const body = (await request.json().catch(() => null)) as { email?: string; companyId?: string }
  const email = body?.email?.trim().toLowerCase()
  const companyId = body?.companyId
  if (!email || !companyId) {
    return NextResponse.json({ error: "Informe e-mail e empresa" }, { 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.users.assignCompany, {
      tenantId: session.user.tenantId ?? "tenant-atlas",
      email,
      companyId: companyId as Id<"companies">,
      actorId: (session.user as unknown as { convexUserId?: Id<"users">; id?: Id<"users"> }).convexUserId ?? (session.user.id as unknown as Id<"users">),
    })
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error("Failed to assign company", error)
    return NextResponse.json({ error: "Falha ao vincular usuário" }, { status: 500 })
  }
}
