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

const CONVEX_URL = process.env.NEXT_PUBLIC_CONVEX_URL
const TENANT_ID = process.env.SEED_TENANT_ID ?? "tenant-atlas"

if (!CONVEX_URL) {
  console.error("NEXT_PUBLIC_CONVEX_URL não definido. Configure o endpoint do Convex e execute novamente.")
  process.exit(1)
}

const TARGET_NAMES = new Set(["Ana Souza", "Bruno Lima"])
const REPLACEMENT = {
  name: "Rever",
  email: "renan.pac@paulicon.com.br",
}

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

  const admin = await client.mutation("users:ensureUser", {
    tenantId: TENANT_ID,
    email: "admin@sistema.dev",
    name: "Administrador",
    role: "ADMIN",
  })

  if (!admin?._id) {
    throw new Error("Não foi possível garantir o usuário administrador")
  }

  const replacementUser = await client.mutation("users:ensureUser", {
    tenantId: TENANT_ID,
    email: REPLACEMENT.email,
    name: REPLACEMENT.name,
    role: "AGENT",
  })

  if (!replacementUser?._id) {
    throw new Error("Não foi possível garantir o usuário Rever")
  }

  const agents = await client.query("users:listAgents", { tenantId: TENANT_ID })
  const targets = agents.filter((agent) => TARGET_NAMES.has(agent.name))

  if (targets.length === 0) {
    console.log("Nenhum responsável legado encontrado. Nada a atualizar.")
  }

  const targetIds = new Set(targets.map((agent) => agent._id))

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

  let reassignedCount = 0
  for (const ticket of tickets) {
    if (ticket.assignee && targetIds.has(ticket.assignee.id)) {
      await client.mutation("tickets:changeAssignee", {
        ticketId: ticket.id,
        assigneeId: replacementUser._id,
        actorId: admin._id,
      })
      reassignedCount += 1
      console.log(`Ticket ${ticket.reference} reatribuído para ${replacementUser.name}`)
    }
  }

  for (const agent of targets) {
    try {
      await client.mutation("users:deleteUser", {
        userId: agent._id,
        actorId: admin._id,
      })
      console.log(`Usuário removido: ${agent.name}`)
    } catch (error) {
      console.error(`Falha ao remover ${agent.name}:`, error)
    }
  }

  console.log(`Total de tickets reatribuídos: ${reassignedCount}`)
}

main().catch((error) => {
  console.error("Erro ao reatribuir responsáveis legacy:", error)
  process.exitCode = 1
})
