import { NextResponse } from "next/server"
import { ConvexHttpClient } from "convex/browser"

import { api } from "@/convex/_generated/api"
import { env } from "@/lib/env"
import { assertAdminSession } from "@/lib/auth-server"

export const runtime = "nodejs"

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

  const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
  const client = new ConvexHttpClient(convexUrl)

  const { searchParams } = new URL(request.url)
  const slugsParam = searchParams.get("slugs")
  if (!slugsParam) return NextResponse.json({ items: {} })
  const slugs = slugsParam.split(",").map((s) => s.trim()).filter(Boolean)

  const tenantId = session.user.tenantId ?? "tenant-atlas"
  try {
    const result = (await client.query(api.alerts.lastForCompaniesBySlugs, { tenantId, slugs })) as Record<string, { createdAt: number; usagePct: number; threshold: number } | null>
    return NextResponse.json({ items: result })
  } catch (error) {
    console.error("Failed to fetch last alerts by slugs", error)
    return NextResponse.json({ items: {} })
  }
}
