import { NextResponse } from "next/server"

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

export const runtime = "nodejs"

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

  const companies = await prisma.company.findMany({
    orderBy: { name: "asc" },
  })
  return NextResponse.json({ companies })
}

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()
  const { name, slug, isAvulso, cnpj, domain, phone, description, address, contractedHoursPerMonth } = body ?? {}
  if (!name || !slug) {
    return NextResponse.json({ error: "Nome e slug são obrigatórios" }, { status: 400 })
  }

  try {
    const company = await prisma.company.create({
      data: ({
        tenantId: session.user.tenantId ?? "tenant-atlas",
        name: String(name),
        slug: String(slug),
        isAvulso: Boolean(isAvulso ?? false),
        contractedHoursPerMonth: typeof contractedHoursPerMonth === "number" ? contractedHoursPerMonth : contractedHoursPerMonth ? Number(contractedHoursPerMonth) : null,
        cnpj: cnpj ? String(cnpj) : null,
        domain: domain ? String(domain) : null,
        phone: phone ? String(phone) : null,
        description: description ? String(description) : null,
        address: address ? String(address) : null,
      } as any),
    })
    return NextResponse.json({ company })
  } catch (error) {
    console.error("Failed to create company", error)
    return NextResponse.json({ error: "Falha ao criar empresa" }, { status: 500 })
  }
}
