const express = require('express');
const multer = require('multer');
const { S3Client, PutObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
const path = require('path');
const crypto = require('crypto');
const authMiddleware = require('../middleware/auth');

const router = express.Router();

// Cloudflare R2 Configuration
const r2Client = new S3Client({
  region: 'auto',
  endpoint: `https://${process.env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.CLOUDFLARE_R2_ACCESS_KEY_ID,
    secretAccessKey: process.env.CLOUDFLARE_R2_SECRET_ACCESS_KEY,
  },
});

// Multer configuration for memory storage
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB limit
  },
  fileFilter: (req, file, cb) => {
    // Only allow image files
    const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    if (allowedMimes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Only image files are allowed (JPEG, PNG, WebP)'), false);
    }
  }
});

// Generate unique filename
const generateFileName = (originalName) => {
  const timestamp = Date.now();
  const random = crypto.randomBytes(8).toString('hex');
  const ext = path.extname(originalName).toLowerCase();
  return `blog-images/${timestamp}-${random}${ext}`;
};

// Upload blog featured image
router.post('/blog-image', authMiddleware, upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: 'No image file provided'
      });
    }

    const fileName = generateFileName(req.file.originalname);
    const bucketName = process.env.CLOUDFLARE_R2_BUCKET_NAME;
    
    if (!bucketName) {
      return res.status(500).json({
        success: false,
        message: 'R2 bucket configuration missing'
      });
    }

    // Upload to Cloudflare R2
    const uploadCommand = new PutObjectCommand({
      Bucket: bucketName,
      Key: fileName,
      Body: req.file.buffer,
      ContentType: req.file.mimetype,
      ContentDisposition: 'inline',
      CacheControl: 'public, max-age=31536000',
    });

    await r2Client.send(uploadCommand);

    // Construct the public URL
    const customDomain = process.env.CLOUDFLARE_R2_CUSTOM_DOMAIN;
    const publicUrl = customDomain 
      ? `https://${customDomain}/${fileName}`
      : `https://${bucketName}.${process.env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com/${fileName}`;

    res.json({
      success: true,
      message: 'Image uploaded successfully',
      data: {
        url: publicUrl,
        filename: fileName,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    });

  } catch (error) {
    console.error('Image upload error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to upload image',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// Delete blog image
router.delete('/blog-image', authMiddleware, async (req, res) => {
  try {
    const { filename } = req.body;
    
    if (!filename) {
      return res.status(400).json({
        success: false,
        message: 'Filename is required'
      });
    }

    const bucketName = process.env.CLOUDFLARE_R2_BUCKET_NAME;

    if (!bucketName) {
      return res.status(500).json({
        success: false,
        message: 'R2 bucket configuration missing'
      });
    }

    const deleteCommand = new DeleteObjectCommand({
      Bucket: bucketName,
      Key: filename,
    });

    await r2Client.send(deleteCommand);

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

  } catch (error) {
    console.error('Image delete error:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to delete image',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

module.exports = router;