import { NextResponse } from "next/server"

import { hashPassword } from "better-auth/crypto"

import { prisma } from "@/lib/prisma"
import { assertStaffSession } from "@/lib/auth-server"
import { isAdmin } from "@/lib/authz"

function generatePassword(length = 12) {
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
  let result = ""
  for (let index = 0; index < length; index += 1) {
    const randomIndex = Math.floor(Math.random() * alphabet.length)
    result += alphabet[randomIndex]
  }
  return result
}

export const runtime = "nodejs"

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const session = await assertStaffSession()
  if (!session) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }
  const sessionIsAdmin = isAdmin(session.user.role)

  const user = await prisma.authUser.findUnique({
    where: { id },
    select: { id: true, role: true },
  })

  if (!user) {
    return NextResponse.json({ error: "Usuário não encontrado" }, { status: 404 })
  }

  const targetRole = (user.role ?? "").toLowerCase()
  if (!sessionIsAdmin && (targetRole === "admin" || targetRole === "agent")) {
    return NextResponse.json({ error: "Você não pode redefinir a senha desse usuário" }, { status: 403 })
  }

  if (targetRole === "machine") {
    return NextResponse.json({ error: "Contas de máquina não possuem senha web" }, { status: 400 })
  }

  const body = (await request.json().catch(() => null)) as { password?: string } | null
  const temporaryPassword = body?.password?.trim() || generatePassword()
  const hashedPassword = await hashPassword(temporaryPassword)

  const credentialAccount = await prisma.authAccount.findFirst({
    where: { userId: user.id, providerId: "credential" },
  })

  if (credentialAccount) {
    await prisma.authAccount.update({ where: { id: credentialAccount.id }, data: { password: hashedPassword } })
  } else {
    // se a conta não existir, cria automaticamente
    const authUser = await prisma.authUser.findUnique({ where: { id: user.id } })
    if (!authUser) {
      return NextResponse.json({ error: "Usuário não encontrado" }, { status: 404 })
    }
    await prisma.authAccount.create({
      data: {
        userId: user.id,
        providerId: "credential",
        accountId: authUser.email,
        password: hashedPassword,
      },
    })
  }

  return NextResponse.json({ temporaryPassword })
}
