import { NextResponse, type NextRequest } from "next/server"
import { getDocumentationCatalog } from "@/lib/documentation/catalog"
import { captureScreenshots } from "@/lib/documentation/screenshot"
import { renderDocumentationDocx } from "@/lib/documentation/docx"

export const runtime = "nodejs"

function getBaseUrl(request: NextRequest) {
  const proto = request.headers.get("x-forwarded-proto") || "http"
  const host = request.headers.get("x-forwarded-host") || request.headers.get("host")
  if (!host) return null
  return `${proto}://${host}`
}

function isAuthorized(request: NextRequest) {
  const token = process.env.DOCUMENTATION_TOKEN
  // If no token is configured, allow access (internal tool)
  if (!token || token === "") return true
  const header = request.headers.get("x-documentation-token")
  const query = request.nextUrl.searchParams.get("token")
  return header === token || query === token
}

export async function POST(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  const baseUrl = getBaseUrl(request)
  if (!baseUrl) {
    return NextResponse.json({ error: "Host is required" }, { status: 400 })
  }

  try {
    const pages = getDocumentationCatalog()
    const screenshots = await captureScreenshots(pages, {
      baseUrl,
      timeoutMs: 60000,
      viewport: { width: 430, height: 932 },
    })
    const docxBuffer = await renderDocumentationDocx(screenshots)

    return new NextResponse(docxBuffer, {
      status: 200,
      headers: {
        "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "Content-Disposition": `attachment; filename="app-documentation.docx"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
