const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Create uploads directory if it doesn't exist
const uploadsDir = path.join(__dirname, '../uploads/drawings');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// Configure storage
const storage = multer.diskStorage({
  destination: async function (req, file, cb) {
    // Get material_id from params or body
    const materialId = req.params.material_id || req.body.material_id;
    let materialNumber = 'temp';
    
    // If material_id is provided, fetch material_number from database
    if (materialId) {
      try {
        const db = require('../models');
        const material = await db.Material.findByPk(materialId, {
          attributes: ['material_number']
        });
        if (material) {
          materialNumber = material.material_number;
        }
      } catch (error) {
        console.error('Error fetching material:', error);
      }
    } else {
      // Fallback to material_number from body
      materialNumber = req.body.material_number || 'temp';
    }
    
    const materialDir = path.join(uploadsDir, materialNumber);
    
    if (!fs.existsSync(materialDir)) {
      fs.mkdirSync(materialDir, { recursive: true });
    }
    
    cb(null, materialDir);
  },
  filename: function (req, file, cb) {
    // Use drawing_number as filename if provided, otherwise use original name
    const drawingNumber = req.body.drawing_number || req.params.drawing_number;
    const revisionNumber = req.body.revision_number || req.params.revision_number;
    
    let filename;
    if (drawingNumber) {
      // Use drawing_number as base filename
      const ext = path.extname(file.originalname);
      filename = drawingNumber;
      if (revisionNumber) {
        filename += `_REV${revisionNumber}`;
      }
      filename += ext;
    } else {
      // Use original filename with timestamp to avoid conflicts
      const ext = path.extname(file.originalname);
      const name = path.basename(file.originalname, ext);
      filename = `${name}_${Date.now()}${ext}`;
    }
    
    cb(null, filename);
  }
});

// File filter - only allow PDF and image files
const fileFilter = (req, file, cb) => {
  const allowedMimeTypes = [
    'application/pdf',
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/gif',
    'image/bmp',
    'image/webp',
    'image/tiff'
  ];
  
  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type. Only PDF and image files (JPEG, PNG, GIF, BMP, WEBP, TIFF) are allowed.'), false);
  }
};

// Configure multer
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit
  }
});

// Middleware for single file upload
const uploadDrawing = upload.single('drawing');

// Print Header Logo Upload Configuration
const printHeaderUploadsDir = path.join(__dirname, '../uploads/print-headers');
if (!fs.existsSync(printHeaderUploadsDir)) {
  fs.mkdirSync(printHeaderUploadsDir, { recursive: true });
}

const printHeaderStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const headerId = req.params.header_id || req.body.header_id || 'temp';
    const headerDir = path.join(printHeaderUploadsDir, headerId.toString());
    
    if (!fs.existsSync(headerDir)) {
      fs.mkdirSync(headerDir, { recursive: true });
    }
    
    cb(null, headerDir);
  },
  filename: function (req, file, cb) {
    const fileType = req.body.file_type || 'logo'; // 'logo' or 'certification'
    const ext = path.extname(file.originalname);
    const name = path.basename(file.originalname, ext);
    const filename = `${fileType}_${name}_${Date.now()}${ext}`;
    cb(null, filename);
  }
});

const printHeaderFileFilter = (req, file, cb) => {
  const allowedMimeTypes = [
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/gif',
    'image/bmp',
    'image/webp',
    'image/svg+xml'
  ];
  
  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type. Only image files (JPEG, PNG, GIF, BMP, WEBP, SVG) are allowed.'), false);
  }
};

const printHeaderUpload = multer({
  storage: printHeaderStorage,
  fileFilter: printHeaderFileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB limit
  }
});

// Middleware for print header logo upload
const uploadPrintHeaderLogo = printHeaderUpload.single('logo');

// Document PDF Upload Configuration
const documentUploadsDir = path.join(__dirname, '../uploads/documents');
if (!fs.existsSync(documentUploadsDir)) {
  fs.mkdirSync(documentUploadsDir, { recursive: true });
}

const documentStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const documentId = req.params.id || req.body.id || 'temp';
    const documentDir = path.join(documentUploadsDir, documentId.toString());
    
    if (!fs.existsSync(documentDir)) {
      fs.mkdirSync(documentDir, { recursive: true });
    }
    
    cb(null, documentDir);
  },
  filename: function (req, file, cb) {
    // Use document_number as filename if provided, otherwise use original name with timestamp
    const documentNumber = req.body.document_number || req.params.document_number;
    const ext = path.extname(file.originalname);
    
    let filename;
    if (documentNumber) {
      // Sanitize document number for filename
      const sanitizedDocNumber = documentNumber.replace(/[^a-zA-Z0-9-_]/g, '_');
      filename = `${sanitizedDocNumber}${ext}`;
    } else {
      const name = path.basename(file.originalname, ext);
      filename = `${name}_${Date.now()}${ext}`;
    }
    
    cb(null, filename);
  }
});

const documentFileFilter = (req, file, cb) => {
  // Only allow PDF files for documents
  if (file.mimetype === 'application/pdf') {
    cb(null, true);
  } else {
    cb(new Error('Invalid file type. Only PDF files are allowed for documents.'), false);
  }
};

const documentUpload = multer({
  storage: documentStorage,
  fileFilter: documentFileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit
  }
});

// Middleware for document PDF upload
const uploadDocumentFile = documentUpload.single('document_file');

// Helper function to get file URL
const getFileUrl = (filePath) => {
  if (!filePath) return null;
  
  // Convert absolute path to relative URL
  const relativePath = filePath.replace(path.join(__dirname, '../uploads'), '');
  return `/uploads${relativePath.replace(/\\/g, '/')}`;
};

// Helper function to get absolute file path
const getFilePath = (relativePath) => {
  if (!relativePath) return null;
  return path.join(__dirname, '../uploads', relativePath);
};

// Helper function to get print header file URL
const getPrintHeaderFileUrl = (filePath) => {
  if (!filePath) return null;
  // If already a URL path, return as is
  if (filePath.startsWith('/uploads')) {
    return filePath;
  }
  // Otherwise construct the URL
  return `/uploads/print-headers${filePath.replace(/\\/g, '/')}`;
};

module.exports = {
  uploadDrawing,
  uploadPrintHeaderLogo,
  uploadDocumentFile,
  getFileUrl,
  getFilePath,
  getPrintHeaderFileUrl,
  uploadsDir,
  printHeaderUploadsDir,
  documentUploadsDir
};

