// import multer from "multer";
// import path from "path";
// import fs from "fs";
// import multerS3 from "multer-s3";
// import { S3Client } from "@aws-sdk/client-s3";
// import { v4 as uuidv4 } from "uuid";
// import { Request } from "express";
// import { CustomRequest } from "../../interfaces/auth";

// // ================================
// // 1. CORE TYPE DEFINITIONS
// // ================================

// // Custom Request interface extending Express Request

// // File validation result structure
// export interface FileValidationResult {
//   isValid: boolean;
//   error?: string;
//   fileInfo?: {
//     originalName: string;
//     mimeType: string;
//     extension: string;
//     size?: number;
//   };
// }

// // Upload configuration structure
// export interface UploadConfig {
//   maxFileSize: number;
//   allowedTypes: string[];
//   allowedExtensions: string[];
//   maxFiles: number;
// }

// // File metadata structure
// export interface FileMetadata {
//   originalName: string;
//   uploadedBy: string;
//   uploadDate: Date;
//   fileSize?: number;
//   mimeType: string;
//   storageLocation: 'local' | 's3';
// }

// // Chunk upload tracking structure
// export interface ChunkUploadState {
//   videoId: string;
//   totalChunks: number;
//   uploadedChunks: Set<number>;
//   chunkPaths: Map<number, string>;
//   isComplete: boolean;
//   metadata: FileMetadata;
// }

// // ================================
// // 2. FIXED TYPE DEFINITIONS FOR MULTER
// // ================================

// // Fix: Use multer's built-in types instead of custom ones
// // The error occurs because multer expects specific callback signatures

// // Remove custom callback types and use multer's built-in ones
// // import { FileFilterCallback } from 'multer'; // Use this instead

// // ================================
// // 3. ENVIRONMENT VALIDATION STRUCTURE
// // ================================

// class EnvironmentValidator {
//   private static requiredVars = [
//     'AWS_REGION',
//     'AWS_ACCESS_KEY_ID', 
//     'AWS_SECRET_ACCESS_KEY',
//     'ASSETS_PATH'
//   ];

//   static validate(): void {
//     const missing: string[] = [];
    
//     // Add S3 bucket requirement for non-test environments
//     const envVars = process.env.NODE_ENV !== 'test' 
//       ? [...this.requiredVars, 'AWS_S3_BUCKET_NAME']
//       : this.requiredVars;

//     for (const envVar of envVars) {
//       if (!process.env[envVar]) {
//         missing.push(envVar);
//       }
//     }

//     if (missing.length > 0) {
//       throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
//     }
//   }
// }

// // ================================
// // 4. FILE UPLOAD MANAGER CLASS
// // ================================

// class FileUploadManager {
//   private config: UploadConfig;
//   private s3Client: S3Client;
//   private chunkStates: Map<string, ChunkUploadState> = new Map();

//   constructor() {
//     EnvironmentValidator.validate();
    
//     this.config = {
//       maxFileSize: 1024 * 1024 * 500, // 500MB
//       maxFiles: 10,
//       allowedTypes: [
//         'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
//         'video/mp4', 'video/mpeg', 'video/quicktime',
//         'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/m4a', 'audio/x-m4a',
//         'application/pdf', 'application/msword', 
//         'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
//         'text/plain', 'application/json', 'application/xml'
//       ],
//       allowedExtensions: [
//         '.jpeg', '.jpg', '.png', '.gif', '.webp',
//         '.mp4', '.mpeg', '.mov',
//         '.mp3', '.wav', '.m4a',
//         '.pdf', '.doc', '.docx',
//         '.txt', '.json', '.xml'
//       ]
//     };

//     this.s3Client = new S3Client({
//       region: process.env.AWS_REGION!,
//       credentials: {
//         accessKeyId: process.env.AWS_ACCESS_KEY_ID!.trim(),
//         secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!.trim(),
//       },
//       maxAttempts: 3,
//       retryMode: 'standard'
//     });
//   }

//   // File validation method
//   validateFile(file: Express.Multer.File): FileValidationResult {
//     const extension = path.extname(file.originalname).toLowerCase();
    
//     const isValidType = this.config.allowedTypes.includes(file.mimetype);
//     const isValidExtension = this.config.allowedExtensions.includes(extension);

//     if (!isValidType || !isValidExtension) {
//       return {
//         isValid: false,
//         error: `Invalid file type. Allowed: ${this.config.allowedTypes.join(', ')}`
//       };
//     }

//     return {
//       isValid: true,
//       fileInfo: {
//         originalName: file.originalname,
//         mimeType: file.mimetype,
//         extension,
//         size: file.size
//       }
//     };
//   }

//   // Chunk upload state management
//   initializeChunkUpload(videoId: string, totalChunks: number, metadata: FileMetadata): void {
//     this.chunkStates.set(videoId, {
//       videoId,
//       totalChunks,
//       uploadedChunks: new Set(),
//       chunkPaths: new Map(),
//       isComplete: false,
//       metadata
//     });
//   }

//   addChunk(videoId: string, chunkIndex: number, chunkPath: string): boolean {
//     const state = this.chunkStates.get(videoId);
//     if (!state) return false;

//     state.uploadedChunks.add(chunkIndex);
//     state.chunkPaths.set(chunkIndex, chunkPath);
    
//     // Check if upload is complete
//     state.isComplete = state.uploadedChunks.size === state.totalChunks;
    
//     return state.isComplete;
//   }

//   getChunkState(videoId: string): ChunkUploadState | undefined {
//     return this.chunkStates.get(videoId);
//   }
// }

// // ================================
// // 5. FIXED MULTER CONFIGURATION
// // ================================

// const uploadManager = new FileUploadManager();

// // Fixed file filter - use multer's built-in callback type
// const fileFilter: multer.Options['fileFilter'] = (req, file, cb) => {
//   try {
//     const validation = uploadManager.validateFile(file);
    
//     if (validation.isValid) {
//       cb(null, true);
//     } else {
//       cb(new Error(validation.error!));
//     }
//   } catch (error) {
//     cb(error as Error);
//   }
// };

// // Local storage configuration
// const localStorage = multer.diskStorage({
//   destination: (req, file, cb) => {
//     try {
//       const uploadPath = path.join(__dirname, '../../public', process.env.ASSETS_PATH!);
      
//       if (!fs.existsSync(uploadPath)) {
//         fs.mkdirSync(uploadPath, { recursive: true });
//       }
      
//       cb(null, uploadPath);
//     } catch (error) {
//       cb(error as Error, '');
//     }
//   },
//   filename: (req, file, cb) => {
//     try {
//       const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`;
//       const ext = path.extname(file.originalname);
//       const name = path.basename(file.originalname, ext).replace(/\s+/g, '-');
//       cb(null, `${name}-${uniqueSuffix}${ext}`);
//     } catch (error) {
//       cb(error as Error, '');
//     }
//   }
// });

// // S3 storage configuration
// const s3Storage = multerS3({
//   s3: uploadManager['s3Client'], // Access private property
//   bucket: process.env.AWS_S3_BUCKET_NAME!,
//   contentType: multerS3.AUTO_CONTENT_TYPE,
//   metadata: (req: CustomRequest, file, cb) => {
//     cb(null, {
//       originalName: file.originalname,
//       uploadedBy: req.userId || 'anonymous'
//     });
//   },
//   key: (req: CustomRequest, file, cb) => {
//     try {
//       const folder = req.body.chunkIndex !== undefined ? 'temp' : 'uploads';
//       const fileId = req.body?.videoId || uuidv4();
//       const ext = path.extname(file.originalname).toLowerCase();
//       const name = path.basename(file.originalname, ext).replace(/\s+/g, '-');
      
//       if (req.body.chunkIndex !== undefined) {
//         cb(null, `${folder}/${fileId}/chunk-${req.body.chunkIndex}${ext}`);
//       } else {
//         cb(null, `${folder}/${fileId}/${name}-${uuidv4()}${ext}`);
//       }
//     } catch (error) {
//       cb(error as Error, '');
//     }
//   }
// });

// // ================================
// // 6. MULTER INSTANCES
// // ================================

// export const localUpload = multer({
//   storage: localStorage,
//   limits: {
//     fileSize: uploadManager['config'].maxFileSize,
//     files: uploadManager['config'].maxFiles
//   },
//   fileFilter
// });

// export const s3Upload = multer({
//   storage: s3Storage,
//   limits: {
//     fileSize: uploadManager['config'].maxFileSize,
//     files: uploadManager['config'].maxFiles
//   },
//   fileFilter
// });

// // ================================
// // 7. UTILITY FUNCTIONS
// // ================================

// export const generateFileName = (originalName: string): string => {
//   const ext = path.extname(originalName);
//   const name = path.basename(originalName, ext).replace(/\s+/g, '-');
//   return `${name}-${Date.now()}${ext}`;
// };

// export const getFileExtension = (filename: string): string => {
//   return path.extname(filename).toLowerCase();
// };

// // ================================
// // 8. ERROR HANDLING
// // ================================

// export interface UploadError {
//   type: 'MULTER_ERROR' | 'VALIDATION_ERROR' | 'SYSTEM_ERROR';
//   code?: string;
//   message: string;
//   details?: any;
// }

// export const handleMulterError = (err: any, req: any, res: any, next: any) => {
//   let errorResponse: UploadError;

//   if (err instanceof multer.MulterError) {
//     errorResponse = {
//       type: 'MULTER_ERROR',
//       code: err.code,
//       message: err.message
//     };
//   } else if (err) {
//     errorResponse = {
//       type: 'SYSTEM_ERROR',
//       message: err.message || 'File upload failed'
//     };
//   } else {
//     return next();
//   }

//   return res.status(400).json({
//     error: 'File upload error',
//     ...errorResponse
//   });
// };

// // ================================
// // 9. EXPORT MANAGER INSTANCE
// // ================================

// export { uploadManager as FileUploadManager };