import { NextResponse } from "next/server"

import { prisma } from "@/lib/prisma"
import { assertAdminSession } from "@/lib/auth-server"

export const runtime = "nodejs"

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await assertAdminSession()
  if (!session) return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  const { id } = await params
  const body = await request.json()

  const updates: Record<string, any> = {}
  for (const key of ["name", "slug", "cnpj", "domain", "phone", "description", "address"]) {
    if (key in body) updates[key] = body[key] ?? null
  }
  if ("isAvulso" in body) updates.isAvulso = Boolean(body.isAvulso)
  if ("contractedHoursPerMonth" in body) {
    const raw = body.contractedHoursPerMonth
    updates.contractedHoursPerMonth = typeof raw === "number" ? raw : raw ? Number(raw) : null
  }

  try {
    const company = await prisma.company.update({ where: { id }, data: updates as any })
    return NextResponse.json({ company })
  } catch (error) {
    console.error("Failed to update company", error)
    return NextResponse.json({ error: "Falha ao atualizar empresa" }, { status: 500 })
  }
}
