import { BadRequestException } from '@nestjs/common';
import type { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
import { extname } from 'node:path';
import { memoryStorage } from 'multer';

// Lets a file through only when BOTH the mime type and the file name say
// it is a PDF. (The upload service later also checks the file content.)
export function pdfFileFilter(
  _request: unknown,
  file: Express.Multer.File,
  callback: (error: Error | null, acceptFile: boolean) => void,
) {
  const hasPdfName = extname(file.originalname).toLowerCase() === '.pdf';
  const hasPdfMimeType = file.mimetype === 'application/pdf';

  if (!hasPdfName || !hasPdfMimeType) {
    callback(new BadRequestException('Only PDF files are allowed'), false);
    return;
  }

  callback(null, true);
}

// Ready-made multer options for PDF uploads. Controllers use this instead
// of writing their own storage/filter/limit configuration:
//   @UseInterceptors(FileInterceptor('document', pdfUploadOptions(MAX_SIZE)))
export function pdfUploadOptions(maxSizeBytes: number): MulterOptions {
  return {
    storage: memoryStorage(),
    fileFilter: pdfFileFilter,
    limits: { fileSize: maxSizeBytes },
  };
}
