import { NextResponse } from "next/server"
import { ConvexHttpClient } from "convex/browser"
import { api } from "@/convex/_generated/api"
import { assertAdminSession } from "@/lib/auth-server"

export const runtime = "nodejs"

export async function POST() {
  const session = await assertAdminSession()
  if (!session) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }

  const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) {
    return NextResponse.json({ error: "CONVEX_URL não configurada" }, { status: 500 })
  }

  try {
    const convex = new ConvexHttpClient(convexUrl)
    const result = await convex.mutation(api.liveChat.fixLegacySessions, {})
    return NextResponse.json({ success: true, result })
  } catch (error) {
    console.error("[fix-chat-sessions] Erro:", error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Falha ao corrigir sessões" },
      { status: 500 }
    )
  }
}
