import { BadRequestException } from "@nestjs/common";
import { randomUUID } from "crypto";
import { diskStorage } from "multer";
import { extname } from "path";

// Shared between the media library's own upload endpoint and the content
// module's inline image uploader (see content.controller.ts) so every
// uploaded file — wherever it's uploaded from — lands in the same
// ./uploads dir with the same validation and ends up in the media library.
// SVG is deliberately excluded: it's an XML document that can carry inline
// <script>, not a raster format, and nothing on the site uses one — the
// classic stored-XSS vector for an "image" upload field isn't worth
// opening for a format we don't need.
export const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);

export const imageUploadOptions = {
  storage: diskStorage({
    destination: "./uploads",
    filename: (_req: unknown, file: Express.Multer.File, cb: (error: Error | null, filename: string) => void) =>
      cb(null, `${randomUUID()}${extname(file.originalname)}`),
  }),
  limits: { fileSize: 8 * 1024 * 1024 },
  fileFilter: (_req: unknown, file: Express.Multer.File, cb: (error: Error | null, acceptFile: boolean) => void) => {
    if (!ALLOWED_IMAGE_TYPES.has(file.mimetype)) {
      cb(new BadRequestException("Only JPEG, PNG, WebP, or GIF images are allowed."), false);
      return;
    }
    cb(null, true);
  },
};
