import { Request, Response, NextFunction } from "express";
import { catchAsyncError } from "./catchAsyncError";
import ErrorHandler from "./error";

export const validateFileUpload = (
  allowedTypes: string[] = [
    "image/jpeg",
    "image/png",
    "image/webp",
    "image/gif",
    "video/mp4",
  ],
  maxSize: number = 10 * 1024 * 1024, // 10MB
) => {
  return catchAsyncError(
    async (req: Request, res: Response, next: NextFunction) => {
      if (!req.files || !req.files.file) {
        return next(new ErrorHandler("No file uploaded", 400));
      }

      const file = Array.isArray(req.files.file)
        ? req.files.file[0]
        : req.files.file;

      // Check file type
      if (!allowedTypes.includes(file.mimetype)) {
        return next(
          new ErrorHandler(
            `Invalid file type. Allowed types: ${allowedTypes.join(", ")}`,
            400,
          ),
        );
      }

      // Check file size
      if (file.size > maxSize) {
        return next(
          new ErrorHandler(
            `File too large. Maximum size: ${maxSize / (1024 * 1024)}MB`,
            400,
          ),
        );
      }

      // Validate image dimensions if it's an image
      if (file.mimetype.startsWith("image/")) {
        // You can add dimension validation here if needed
        // For example, check minimum/maximum width/height
      }

      next();
    },
  );
};

export const validateMultipleFiles = (
  maxFiles: number = 10,
  allowedTypes: string[] = [
    "image/jpeg",
    "image/png",
    "image/webp",
    "image/gif",
    "video/mp4",
  ],
  maxSize: number = 10 * 1024 * 1024, // 10MB
) => {
  return catchAsyncError(
    async (req: Request, res: Response, next: NextFunction) => {
      if (!req.files || !req.files.files) {
        return next(new ErrorHandler("No files uploaded", 400));
      }

      const files = Array.isArray(req.files.files)
        ? req.files.files
        : [req.files.files];

      // Check number of files
      if (files.length > maxFiles) {
        return next(new ErrorHandler(`Maximum ${maxFiles} files allowed`, 400));
      }

      // Validate each file
      for (const file of files) {
        if (!allowedTypes.includes(file.mimetype)) {
          return next(
            new ErrorHandler(
              `Invalid file type for ${file.name}. Allowed types: ${allowedTypes.join(", ")}`,
              400,
            ),
          );
        }

        if (file.size > maxSize) {
          return next(
            new ErrorHandler(
              `File ${file.name} too large. Maximum size: ${maxSize / (1024 * 1024)}MB`,
              400,
            ),
          );
        }
      }

      next();
    },
  );
};
