import { randomBytes } from "crypto";
import * as path from "path";

import { Router } from "express";
import multer, { FileFilterCallback } from "multer";

import { ALLOWED_CONTENT_TYPES, MAX_FILE_SIZE_IN_BYTES } from "./posterHandler";

// Dev-harness-only: the real contract has the *upstream backend* host
// posters and hand us a sourceUrl. Since no real upstream exists yet, the
// frontend test harness needs somewhere to put a file the user picked so it
// can produce that sourceUrl itself -- this is that somewhere. Not part of
// the documented CSC Event PR Service contract.
export const UPLOAD_DIR = path.join(__dirname, "..", "uploads");

const fileFilter = (_req: unknown, file: Express.Multer.File, callback: FileFilterCallback) => {
  if (!ALLOWED_CONTENT_TYPES.includes(file.mimetype)) {
    callback(new Error(`Unsupported file type "${file.mimetype}"`));
    return;
  }
  callback(null, true);
};

// Preserve the original extension so express.static (and our own
// downstream fetch of it) infer the right Content-Type -- multer's default
// dest-only storage drops it, which would make everything look like
// application/octet-stream.
const storage = multer.diskStorage({
  destination: UPLOAD_DIR,
  filename: (_req, file, callback) => callback(null, `${Date.now()}--${file.originalname}`),
});

const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: MAX_FILE_SIZE_IN_BYTES },
});

export const uploadRouter = Router();

uploadRouter.post("/api/dev-uploads", upload.single("poster"), (req, res) => {
  if (!req.file) {
    res.status(400).json({ error: { code: "MISSING_FILE", message: "No file uploaded under field 'poster'" } });
    return;
  }

  const publicBase = process.env.PUBLIC_BASE_URL ?? `http://localhost:${process.env.PORT ?? 8001}`;
  res.json({
    sourceUrl: `${publicBase}/uploads/${req.file.filename}`,
    filename: `${randomBytes(4).toString("hex")}-${req.file.originalname}`,
    contentType: req.file.mimetype,
  });
});
