import express from "express";
import helmet from "helmet";
import { extname, resolve } from "node:path";

const app = express();
const port = Number.parseInt(process.env.PORT || "8080", 10);
const downloadsRoot = resolve("/app/downloads");

app.disable("x-powered-by");
app.set("trust proxy", true);

app.use(
  helmet({
    contentSecurityPolicy: false,
    crossOriginEmbedderPolicy: false,
    crossOriginResourcePolicy: { policy: "cross-origin" }
  })
);

app.get("/health", (_request, response) => {
  response.setHeader("Cache-Control", "no-store");
  response.json({ ok: true });
});

app.use(
  "/downloads",
  express.static(downloadsRoot, {
    dotfiles: "deny",
    fallthrough: false,
    index: false,
    setHeaders(response, filePath) {
      const extension = extname(filePath).toLowerCase();

      if (extension === ".apk") {
        response.setHeader("Content-Type", "application/vnd.android.package-archive");
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        return;
      }

      response.setHeader("Cache-Control", "public, max-age=300");
    }
  })
);

app.use((request, response) => {
  const isDownloadsPath = request.path === "/downloads" || request.path.startsWith("/downloads/");

  response
    .status(isDownloadsPath ? 404 : 404)
    .setHeader("Cache-Control", "no-store")
    .json({ message: isDownloadsPath ? "File not found" : "Not found" });
});

app.listen(port, "0.0.0.0", () => {
  console.log(`Downloads service listening on ${port}`);
});
