import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/session"
import { getEffectiveOwnerId } from "@/lib/account"
import { readFile, contentTypeForKey, usingSpaces, presignGetUrl } from "@/lib/storage"

// Only these image types are safe to render inline from our origin. Everything
// else (including svg, html, documents) is forced to download as an attachment.
const INLINE_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp"]

// Auth-gated file serving. Storage keys are namespaced by the portfolio's owner
// id (`<ownerId>/<scope>/<file>`), so a file belongs to the requester iff the
// key's first segment equals their EFFECTIVE owner id — this lets active team
// members view the owner's files while preserving isolation between accounts.
//
// When object storage (Spaces) is configured we issue a short-lived presigned
// redirect so the bytes stream straight from the bucket to the browser instead
// of through the app. The auth + ownership checks below still gate every request
// (the presigned URL is only minted for the rightful owner and expires quickly).
export async function GET(_: Request, { params }: { params: Promise<{ key: string[] }> }) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

  const ownerId = await getEffectiveOwnerId(user.id)

  const { key: segments } = await params

  // Reject traversal / malformed segments (no double-decode — params are already decoded).
  const badSegment = segments.some(
    (s) => s === "" || s === "." || s === ".." || s.includes("/") || s.includes("\\")
  )
  // Ownership: the first path segment must be EXACTLY the caller's effective owner id.
  if (badSegment || segments[0] !== ownerId) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  }

  const key = segments.join("/")
  const ext = key.split(".").pop()?.toLowerCase() ?? ""
  const disposition = INLINE_EXTENSIONS.includes(ext) ? "inline" : "attachment"
  const basename = (key.split("/").pop() ?? "file").replace(/["\\\r\n]/g, "")

  // Object storage: redirect to a presigned URL (bytes served by Spaces).
  if (usingSpaces()) {
    try {
      const url = await presignGetUrl(key, { disposition, filename: basename, expiresIn: 3600 })
      const res = NextResponse.redirect(url, 302)
      // Let the browser reuse the redirect for a while (< the URL's TTL) so
      // repeat views skip the app hop entirely, without outliving the signature.
      res.headers.set("Cache-Control", "private, max-age=1800")
      return res
    } catch {
      return NextResponse.json({ error: "Not found" }, { status: 404 })
    }
  }

  // Local-disk fallback: stream the bytes through the app.
  try {
    const buffer = await readFile(key)
    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": contentTypeForKey(key),
        "Content-Disposition": `${disposition}; filename="${basename}"`,
        "X-Content-Type-Options": "nosniff",
        "Cache-Control": "private, max-age=3600",
      },
    })
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404 })
  }
}
