import { NextResponse } from "next/server"

import { requireAuthenticatedSession } from "@/lib/auth-server"
import { isStaff } from "@/lib/authz"
import { env } from "@/lib/env"
import { exportResolvedTicketsToDisk } from "@/server/archive/local-tickets"

function getCronSecret(): string | null {
  return env.INTERNAL_HEALTH_TOKEN ?? env.REPORTS_CRON_SECRET ?? null
}

export async function POST(request: Request) {
  const cronSecret = getCronSecret()
  const headerSecret = request.headers.get("x-cron-secret")?.trim()

  let isCron = false
  if (cronSecret && headerSecret && headerSecret === cronSecret) {
    isCron = true
  }

  if (!isCron) {
    const session = await requireAuthenticatedSession()
    const role = session.user.role ?? "agent"
    if (!isStaff(role)) {
      return NextResponse.json({ error: "Acesso negado" }, { status: 403 })
    }
  }

  let body: { days?: number; limit?: number } = {}
  try {
    body = (await request.json()) ?? {}
  } catch {
    body = {}
  }

  const days = typeof body.days === "number" && body.days > 0 ? body.days : 365
  const limit = typeof body.limit === "number" && body.limit > 0 ? body.limit : 50

  try {
    const result = await exportResolvedTicketsToDisk({ days, limit })
    return NextResponse.json({ ok: true, ...result }, { status: 200 })
  } catch (error) {
    console.error("[admin.tickets.archive-local] failed", error)
    return NextResponse.json(
      {
        error: "Falha ao arquivar tickets",
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    )
  }
}
