import { ALLOWED_IMAGE_TYPES } from "@/lib/media/constants";
import { readLocalFile } from "@/lib/storage/local";

const CONTENT_TYPES = Object.fromEntries(
  Object.entries(ALLOWED_IMAGE_TYPES).map(([type, extension]) => [extension, type]),
);

/**
 * Serves files saved by the local storage driver. Files uploaded after a
 * build are not in `public/`, so they need a route. With the S3 driver,
 * images are served by the bucket instead and this route finds nothing.
 */
export async function GET(
  _request: Request,
  { params }: RouteContext<"/uploads/[...key]">,
) {
  const key = (await params).key.join("/");
  const file = await readLocalFile(key);
  const extension = key.split(".").pop() ?? "";
  const contentType = CONTENT_TYPES[extension];

  if (!file || !contentType) {
    return new Response("Not found", { status: 404 });
  }

  return new Response(new Uint8Array(file), {
    headers: {
      "content-type": contentType,
      "content-length": String(file.byteLength),
      // Keys are unique per upload, so a stored file never changes.
      "cache-control": "public, max-age=31536000, immutable",
      "x-content-type-options": "nosniff",
      "content-security-policy": "default-src 'none'; sandbox",
      // The website embeds these images from another origin.
      "cross-origin-resource-policy": "cross-origin",
    },
  });
}
