import { NextResponse } from "next/server"

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

function getInternalSecret() {
  return env.INTERNAL_HEALTH_TOKEN ?? env.REPORTS_CRON_SECRET ?? null
}

export async function GET(_: Request, context: { params: { ticketId: string } }) {
  const cronSecret = getInternalSecret()
  const headerSecret = _.headers.get("x-cron-secret")?.trim()
  const querySecret = new URL(_.url).searchParams.get("token")?.trim()

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

  const ticketId = context.params.ticketId
  const found = await findArchivedTicket(ticketId)
  if (!found) {
    return NextResponse.json({ error: "Ticket arquivado não encontrado" }, { status: 404 })
  }

  return NextResponse.json(
    {
      ok: true,
      ticketId,
      file: found.file,
      archivedAt: found.record.archivedAt,
      tenantId: found.record.tenantId,
      ticket: found.record.ticket,
      comments: found.record.comments,
      events: found.record.events,
      attachments: (found.record as { attachments?: unknown }).attachments ?? [],
    },
    { status: 200 }
  )
}
