// src/middleware/fileUpload.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { ValidationError } from '../services/db/errors.db';

/**
 * Middleware to check if a file was uploaded by multer.
 * @param fieldName The expected field name of the uploaded file.
 */
export const requireFileUpload = (fieldName: string) => (req: Request, res: Response, next: NextFunction) => {
  if (!req.file || req.file.fieldname !== fieldName) {
    // Use ValidationError for consistency with ADR-003.
    // The errorHandler will format this into a 400 response with a structured error.
    const validationIssue = {
      path: ['file', fieldName],
      message: `A file for the '${fieldName}' field is required.`,
    };
    return next(new ValidationError([validationIssue]));
  }
  next();
};