import "dotenv/config"
import { PrismaClient } from "@prisma/client"
import { ConvexHttpClient } from "convex/browser"

const prisma = new PrismaClient()

const tenantId = process.env.SYNC_TENANT_ID || "tenant-atlas"
const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL || "http://127.0.0.1:3210"
const secret = process.env.CONVEX_SYNC_SECRET

if (!secret) {
  console.error("CONVEX_SYNC_SECRET não configurado. Configure-o para executar o prune.")
  process.exit(1)
}

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

  const prismaCompanies = await prisma.company.findMany({
    where: { tenantId },
    select: { slug: true },
  })
  const validSlugs = new Set(prismaCompanies.map((company) => company.slug))

  const snapshot = await client.query("migrations:exportTenantSnapshot", {
    tenantId,
    secret,
  })

  const extraCompanies = snapshot.companies.filter((company) => !validSlugs.has(company.slug))
  if (extraCompanies.length === 0) {
    console.log("Nenhuma empresa extra encontrada no Convex.")
    return
  }

  console.log(`Removendo ${extraCompanies.length} empresa(s) do Convex: ${extraCompanies.map((c) => c.slug).join(", ")}`)

  for (const company of extraCompanies) {
    await client.mutation("companies:removeBySlug", {
      tenantId,
      slug: company.slug,
    })
  }
  console.log("Concluído.")
}

main()
  .catch((error) => {
    console.error("Falha ao remover empresas extras do Convex", error)
    process.exitCode = 1
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
