import "dotenv/config"
import pkg from "@prisma/client"
import { hashPassword } from "better-auth/crypto"

const { PrismaClient } = pkg
const prisma = new PrismaClient()

// Em produção, evitar sobrescrever senhas a cada deploy.
// Por padrão, apenas GARANTE que o usuário e a conta existam (sem resetar senha).
const ensureOnly = (process.env.SEED_ENSURE_ONLY ?? "true").toLowerCase() === "true"

const tenantId = process.env.SEED_USER_TENANT ?? "tenant-atlas"

const singleUserFromEnv = process.env.SEED_USER_EMAIL
  ? [{
      email: process.env.SEED_USER_EMAIL,
      password: process.env.SEED_USER_PASSWORD ?? "admin123",
      name: process.env.SEED_USER_NAME ?? "Administrador",
      role: process.env.SEED_USER_ROLE ?? "admin",
      tenantId,
    }]
  : null

const defaultUsers = singleUserFromEnv ?? [
  {
    email: "admin@sistema.dev",
    password: "admin123",
    name: "Administrador",
    role: "admin",
    tenantId,
  },
  {
    email: "gabriel.oliveira@rever.com.br",
    password: "agent123",
    name: "Gabriel Oliveira",
    role: "agent",
    tenantId,
  },
  {
    email: "george.araujo@rever.com.br",
    password: "agent123",
    name: "George Araujo",
    role: "agent",
    tenantId,
  },
  {
    email: "hugo.soares@rever.com.br",
    password: "agent123",
    name: "Hugo Soares",
    role: "agent",
    tenantId,
  },
  {
    email: "julio@rever.com.br",
    password: "agent123",
    name: "Julio Cesar",
    role: "agent",
    tenantId,
  },
  {
    email: "lorena@rever.com.br",
    password: "agent123",
    name: "Lorena Magalhães",
    role: "agent",
    tenantId,
  },
  {
    email: "renan.pac@paulicon.com.br",
    password: "agent123",
    name: "Rever",
    role: "agent",
    tenantId,
  },
  {
    email: "suporte@rever.com.br",
    password: "agent123",
    name: "Telão",
    role: "agent",
    tenantId,
  },
  {
    email: "thiago.medeiros@rever.com.br",
    password: "agent123",
    name: "Thiago Medeiros",
    role: "agent",
    tenantId,
  },
  {
    email: "weslei@rever.com.br",
    password: "agent123",
    name: "Weslei Magalhães",
    role: "agent",
    tenantId,
  },
]

async function ensureCredentialAccount(userId, email, hashedPassword, updatePassword) {
  const existing = await prisma.authAccount.findFirst({
    where: { userId, providerId: "credential", accountId: email },
  })
  if (existing) {
    if (updatePassword) {
      await prisma.authAccount.update({
        where: { id: existing.id },
        data: { password: hashedPassword },
      })
    }
    return existing
  }
  return prisma.authAccount.create({
    data: {
      userId,
      providerId: "credential",
      accountId: email,
      password: hashedPassword,
    },
  })
}

async function ensureAuthUser({ email, password, name, role, tenantId: userTenant }) {
  const hashedPassword = await hashPassword(password)

  const existing = await prisma.authUser.findUnique({ where: { email } })
  if (!existing) {
    const user = await prisma.authUser.create({
      data: {
        email,
        name,
        role,
        tenantId: userTenant,
        accounts: {
          create: {
            providerId: "credential",
            accountId: email,
            password: hashedPassword,
          },
        },
      },
      include: { accounts: true },
    })
    console.log(`✅ Usuario criado: ${user.email}`)
    console.log(`   ID: ${user.id}`)
    console.log(`   Role: ${user.role}`)
    console.log(`   Tenant: ${user.tenantId ?? "(nenhum)"}`)
    console.log(`   Senha provisoria: ${password}`)
    return
  }

  // Usuário já existe
  if (!ensureOnly) {
    await prisma.authUser.update({
      where: { id: existing.id },
      data: { name, role, tenantId: userTenant },
    })
  }

  await ensureCredentialAccount(existing.id, email, hashedPassword, !ensureOnly)
  console.log(`✅ Usuario garantido${ensureOnly ? " (sem reset de senha)" : " (atualizado)"}: ${email}`)
}

async function main() {
  for (const user of defaultUsers) {
    await ensureAuthUser(user)
  }
}

main()
  .catch((error) => {
    console.error("Erro ao criar usuario seed", error)
    process.exitCode = 1
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
