import { NextRequest, NextResponse } from "next/server"

import { createConvexClient } from "@/server/convex-client"
import { api } from "@/convex/_generated/api"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

// Endpoint para encerrar sessoes de chat inativas
// Substitui o cron job do Convex para evitar acumulo de registros em _scheduled_job_logs
// Chamado via crontab do Linux:
// * * * * * curl -s "https://tickets.esdrasrenan.com.br/api/cron/chat-cleanup" -H "x-cron-secret: $CRON_SECRET" >/dev/null 2>&1

export async function GET(request: NextRequest) {
  // Verificar secret no header
  const authHeader = request.headers.get("x-cron-secret")
  const expectedSecret = process.env.CRON_SECRET || process.env.REPORTS_CRON_SECRET

  if (!expectedSecret) {
    return NextResponse.json(
      { error: "CRON_SECRET nao configurado no servidor" },
      { status: 500 }
    )
  }

  if (authHeader !== expectedSecret) {
    return NextResponse.json(
      { error: "Nao autorizado" },
      { status: 401 }
    )
  }

  try {
    const convex = createConvexClient()
    const result = await convex.mutation(api.liveChat.autoEndInactiveSessions, {})

    return NextResponse.json({
      success: true,
      message: "Sessoes de chat inativas encerradas",
      result,
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    console.error("Erro ao executar chat-cleanup:", error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    )
  }
}
