import "dotenv/config"
import bcrypt from "bcrypt"
import { PrismaClient, UserRole, TenantStatus } from "@prisma/client"
import { PrismaPg } from "@prisma/adapter-pg"
import { Pool } from "pg"

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
})

const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })


async function main() {
  // Ajuste aqui se quiser
  const adminEmail = "admin@meile.com.br"
  const adminPass = "Admin@2025!"
  const adminName = "Admin Suporte"

  const clientEmail = "cliente@exemplo.com.br"
  const clientPass = "Cliente@2025!"
  const clientName = "Cliente Admin"

  const adminHash = await bcrypt.hash(adminPass, 12)
  const clientHash = await bcrypt.hash(clientPass, 12)

  // Tenant interno (suporte)
  const suporteTenant = await prisma.tenant.upsert({
    where: { id: "tenant-suporte" },
    update: {},
    create: {
      id: "tenant-suporte",
      name: "Meile (Suporte)",
      status: TenantStatus.ACTIVE,
    },
  })

  // Usuário ADMIN (sem tenantId, porque é staff global)
  await prisma.user.upsert({
    where: { email: adminEmail },
    update: {
      name: adminName,
      role: UserRole.ADMIN,
      password: adminHash,
    },
    create: {
      email: adminEmail,
      name: adminName,
      role: UserRole.ADMIN,
      password: adminHash,
      tenantId: null,
    },
  })

  // Tenant cliente exemplo
  const tenantCliente = await prisma.tenant.upsert({
    where: { id: "tenant-exemplo" },
    update: {},
    create: {
      id: "tenant-exemplo",
      name: "Exemplo LTDA",
      status: TenantStatus.ACTIVE,
    },
  })

  // Usuário CLIENT_ADMIN (amarrado ao tenant)
  await prisma.user.upsert({
    where: { email: clientEmail },
    update: {
      name: clientName,
      role: UserRole.CLIENT_ADMIN,
      password: clientHash,
      tenantId: tenantCliente.id,
    },
    create: {
      email: clientEmail,
      name: clientName,
      role: UserRole.CLIENT_ADMIN,
      password: clientHash,
      tenantId: tenantCliente.id,
    },
  })

  console.log("Seed concluído ✅")
  console.log("ADMIN:", adminEmail, adminPass)
  console.log("CLIENTE:", clientEmail, clientPass)
  console.log("Tenant suporte:", suporteTenant.name)
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
  await prisma.$disconnect()
  await pool.end()
})

