import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const ALLOWED_EXTENSIONS = new Set([
  // Images
  'jpg', 'jpeg', 'png', 'webp', 'gif', 'svg',
  // PDF
  'pdf',
  // Word & Documents
  'doc', 'docx', 'txt', 'rtf',
  // Excel & Spreadsheets
  'xls', 'xlsx', 'csv'
]);

const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB in bytes

export async function uploadImage(req, res) {
  try {
    const { name, type, data, image, file } = req.body;
    const fileContent = data || image || file;
    if (!fileContent) {
      return res.status(400).json({ error: "Missing uploaded file content." });
    }

    // Extract and validate extension
    let ext = (name ? name.split('.').pop() : '').toLowerCase();
    if (!ext || !ALLOWED_EXTENSIONS.has(ext)) {
      if (type && type.includes('/')) {
        ext = type.split('/')[1].toLowerCase();
      } else if (typeof fileContent === 'string' && fileContent.startsWith('data:image/')) {
        ext = fileContent.substring(11, fileContent.indexOf(';')).toLowerCase();
      }
      if (ext === 'jpeg') ext = 'jpg';
    }
    if (!ext || !ALLOWED_EXTENSIONS.has(ext)) {
      ext = 'jpg';
    }

    // Strip base64 headers
    const base64Data = String(fileContent).replace(/^data:[^;]+;base64,/, "");
    const buffer = Buffer.from(base64Data, 'base64');

    // Validate file size limit: 5MB
    if (buffer.length > MAX_FILE_SIZE) {
      return res.status(400).json({ 
        error: `File size exceeds the 5MB maximum limit (${(buffer.length / (1024 * 1024)).toFixed(2)}MB).` 
      });
    }

    // Reliable folder path on both local and cPanel / Phusion Passenger environments
    const uploadDir = path.resolve(__dirname, '..', 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // Generate randomized unique path file name
    const safeBaseName = (name ? name.replace(/\.[^/.]+$/, "") : "file")
      .replace(/[^a-zA-Z0-9_-]/g, "_")
      .substring(0, 30);
    const filename = `${Date.now()}-${safeBaseName}-${Math.random().toString(36).substring(2, 7)}.${ext}`;
    const filepath = path.join(uploadDir, filename);

    // Write file to filesystem
    fs.writeFileSync(filepath, buffer);

    // Dynamically resolve base URL (supports cPanel reverse proxy, custom domains, and local dev)
    const protocol = req.headers['x-forwarded-proto'] || req.protocol || 'http';
    const host = req.get('host');
    const baseUrl = process.env.APP_URL || process.env.BASE_URL || `${protocol}://${host}`;
    const fileUrl = `${baseUrl.replace(/\/+$/, '')}/uploads/${filename}`;

    return res.json({ 
      url: fileUrl,
      relative_url: `/uploads/${filename}`,
      name: name || filename,
      size: buffer.length,
      ext: ext,
      type: type || `application/${ext}`
    });
  } catch (err) {
    console.error("uploadFile error:", err);
    return res.status(500).json({ error: "Internal server error saving uploaded file." });
  }
}
