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

import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { prisma } from "@/lib/prisma"

export const runtime = "nodejs"

type Ctx = RouteContext<"/api/reports/schedules/runs/[id]">

export async function GET(request: NextRequest, ctx: Ctx) {
  const { id } = await ctx.params
  const session = await assertAdminSession()
  if (!session) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }
  const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
  const run = await prisma.reportExportRun.findFirst({
    where: { id, tenantId },
  })
  if (!run || !run.artifacts) {
    return NextResponse.json({ error: "Arquivo não encontrado" }, { status: 404 })
  }

  const { searchParams } = new URL(request.url)
  const artifactIndex = Number(searchParams.get("artifact") ?? "0")
  const artifacts = run.artifacts as Array<{ key: string; fileName: string; mimeType: string; data: string }>
  const artifact = artifacts?.[artifactIndex]
  if (!artifact) {
    return NextResponse.json({ error: "Arquivo não encontrado" }, { status: 404 })
  }

  const buffer = Buffer.from(artifact.data, "base64")
  return new NextResponse(buffer, {
    headers: {
      "Content-Type": artifact.mimeType ?? "application/octet-stream",
      "Content-Disposition": `attachment; filename="${artifact.fileName ?? `export-${run.id}`}"`,
      "Cache-Control": "no-store",
    },
  })
}
