const express = require('express');
const router = express.Router();
const upload = require('../middleware/upload');
const path = require('path');
const fs = require('fs');
const authMiddleware = require('../middleware/auth');
const adminAuthMiddleware = require('../middleware/adminAuth');

module.exports = (pool, query) => {
  // Apply authentication for all admin upload routes
  router.use('/admin', adminAuthMiddleware(pool, query));

  // Upload product image (admin only)
  router.post('/admin/products', upload.single('image'), async (req, res, next) => {
    try {
      if (!req.file) {
        return res.status(400).json({
          error: true,
          message: 'No image file provided'
        });
      }

      // Get the relative path to the image
      const imagePath = `/uploads/products/${req.file.filename}`;

      res.json({
        success: true,
        imagePath,
        filename: req.file.filename
      });
    } catch (error) {
      next(error);
    }
  });

  // Upload multiple product images (admin only)
  router.post('/admin/products/multiple', upload.array('images', 10), async (req, res, next) => {
    try {
      if (!req.files || req.files.length === 0) {
        return res.status(400).json({
          error: true,
          message: 'No image files provided'
        });
      }

      // Get the relative paths to the images
      const imagePaths = req.files.map(file => ({
        imagePath: `/uploads/products/${file.filename}`,
        filename: file.filename
      }));

      res.json({
        success: true,
        images: imagePaths
      });
    } catch (error) {
      next(error);
    }
  });

  // Delete product image (admin only)
  router.delete('/admin/products/:filename', async (req, res, next) => {
    try {
      const { filename } = req.params;
      
      // Prevent path traversal attacks
      if (filename.includes('..') || filename.includes('/')) {
        return res.status(400).json({
          error: true,
          message: 'Invalid filename'
        });
      }

      const filePath = path.join(__dirname, '../../public/uploads/products', filename);

      // Check if file exists
      if (!fs.existsSync(filePath)) {
        return res.status(404).json({
          error: true,
          message: 'Image not found'
        });
      }

      // Delete the file
      fs.unlinkSync(filePath);

      res.json({
        success: true,
        message: 'Image deleted successfully'
      });
    } catch (error) {
      next(error);
    }
  });

  // Upload blog post image (admin only)
router.post('/admin/blog', adminAuthMiddleware(pool, query), upload.single('image'), async (req, res, next) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        error: true,
        message: 'No image file provided'
      });
    }

    // Get the relative path to the image
    const imagePath = `/uploads/blog/${req.file.filename}`;

    res.json({
      success: true,
      imagePath,
      filename: req.file.filename
    });
  } catch (error) {
    next(error);
  }
});

  // Upload multiple blog images (admin only)
  router.post('/admin/blog/multiple', adminAuthMiddleware(pool, query), upload.array('images', 10), async (req, res, next) => {
    try {
      if (!req.files || req.files.length === 0) {
        return res.status(400).json({
          error: true,
          message: 'No image files provided'
        });
      }

      // Get the relative paths to the images
      const imagePaths = req.files.map(file => ({
        imagePath: `/uploads/blog/${file.filename}`,
        filename: file.filename
      }));

      res.json({
        success: true,
        images: imagePaths
      });
    } catch (error) {
      next(error);
    }
  });

  // Delete blog image (admin only)
  router.delete('/admin/blog/:filename', adminAuthMiddleware(pool, query), async (req, res, next) => {
    try {
      const { filename } = req.params;
      
      // Prevent path traversal attacks
      if (filename.includes('..') || filename.includes('/')) {
        return res.status(400).json({
          error: true,
          message: 'Invalid filename'
        });
      }

      const filePath = path.join(__dirname, '../../public/uploads/blog', filename);

      // Check if file exists
      if (!fs.existsSync(filePath)) {
        return res.status(404).json({
          error: true,
          message: 'Image not found'
        });
      }

      // Delete the file
      fs.unlinkSync(filePath);

      res.json({
        success: true,
        message: 'Image deleted successfully'
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
};