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

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

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

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

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

  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,
  }
}

type EnsureCollaboratorAccountParams = {
  email: string
  name: string
  tenantId: string
  companyId?: string | null
  role?: "ADMIN" | "MANAGER" | "AGENT" | "COLLABORATOR"
}

export async function ensureCollaboratorAccount(params: EnsureCollaboratorAccountParams) {
  const normalizedEmail = params.email.trim().toLowerCase()
  const name = params.name.trim() || normalizedEmail
  const tenantId = params.tenantId
  const targetRole = (params.role ?? "COLLABORATOR").toUpperCase() as "ADMIN" | "MANAGER" | "AGENT" | "COLLABORATOR"
  const authRole = targetRole.toLowerCase()

  const existingAuth = await prisma.authUser.findUnique({ where: { email: normalizedEmail } })
  const authUser = existingAuth
    ? await prisma.authUser.update({
        where: { id: existingAuth.id },
        data: {
          name,
          tenantId,
          role: authRole,
        },
      })
    : await prisma.authUser.create({
        data: {
          email: normalizedEmail,
          name,
          tenantId,
          role: authRole,
        },
      })

  await prisma.authAccount.upsert({
    where: {
      providerId_accountId: {
        providerId: "credential",
        accountId: normalizedEmail,
      },
    },
    update: {
      userId: authUser.id,
    },
    create: {
      providerId: "credential",
      accountId: normalizedEmail,
      userId: authUser.id,
      password: null,
    },
  })

  await prisma.user.upsert({
    where: { email: normalizedEmail },
    update: {
      name,
      tenantId,
      role: targetRole,
      companyId: params.companyId ?? undefined,
    },
    create: {
      email: normalizedEmail,
      name,
      tenantId,
      role: targetRole,
      companyId: params.companyId ?? undefined,
    },
  })

  return { authUserId: authUser.id }
}
