import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"

type EnsureMachineAccountParams = {
  machineId: string
  tenantId: string
  hostname: string
  machineToken: string
}

export async function ensureMachineAccount(params: EnsureMachineAccountParams) {
  const { machineId, tenantId, hostname, machineToken } = params
  const machineEmail = `machine-${machineId}@machines.local`
  const context = await auth.$context

  const passwordHash = await context.password.hash(machineToken)
  const machineName = `Máquina ${hostname}`

  const user = await prisma.authUser.upsert({
    where: { email: machineEmail },
    update: {
      name: machineName,
      tenantId,
      role: "machine",
    },
    create: {
      email: machineEmail,
      name: machineName,
      role: "machine",
      tenantId,
    },
  })

  await prisma.authAccount.upsert({
    where: {
      providerId_accountId: {
        providerId: "credential",
        accountId: machineEmail,
      },
    },
    update: {
      password: passwordHash,
      userId: user.id,
    },
    create: {
      providerId: "credential",
      accountId: machineEmail,
      userId: user.id,
      password: passwordHash,
    },
  })

  await prisma.authSession.deleteMany({
    where: { userId: user.id },
  })

  return {
    authUserId: user.id,
    authEmail: machineEmail,
  }
}
