import "dotenv/config"
import { ConvexHttpClient } from "convex/browser"

const tenantId = process.env.SYNC_TENANT_ID || "tenant-atlas"
const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL

if (!convexUrl) {
  console.error("NEXT_PUBLIC_CONVEX_URL não configurado. Ajuste o .env antes de executar o script.")
  process.exit(1)
}

const DEFAULT_QUEUES = [
  { name: "Chamados" },
  { name: "Laboratório" },
  { name: "Visitas" },
]

function slugify(value) {
  return value
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^\w\s-]/g, "")
    .trim()
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .toLowerCase()
}

async function main() {
  const client = new ConvexHttpClient(convexUrl)

  const agents = await client.query("users:listAgents", { tenantId })
  const admin =
    agents.find((user) => (user.role ?? "").toUpperCase() === "ADMIN") ??
    agents[0]

  if (!admin?._id) {
    console.error("Nenhum usuário ADMIN encontrado no Convex para criar filas padrão.")
    process.exit(1)
  }

  const existing = await client.query("queues:list", {
    tenantId,
    viewerId: admin._id,
  })

  const existingSlugs = new Set(existing.map((queue) => queue.slug))
  const created = []

  for (const def of DEFAULT_QUEUES) {
    const slug = slugify(def.name)
    if (existingSlugs.has(slug)) {
      continue
    }
    await client.mutation("queues:create", {
      tenantId,
      actorId: admin._id,
      name: def.name,
    })
    created.push(def.name)
  }

  if (created.length === 0) {
    console.log("Nenhuma fila criada. As filas padrão já existem.")
  } else {
    console.log(`Filas criadas: ${created.join(", ")}`)
  }
}

main().catch((error) => {
  console.error("Falha ao garantir filas padrão", error)
  process.exit(1)
})
